Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Enhancing a Simple PHP Application Adding Search: Model Performing the Search

Aaron Bini
Aaron Bini
12,129 Points

strpos search an array within an array

If I have an array within my $haystack array, how do I get the strpos function to search for $needle within this inner arrray? For example, I have a variable of $stores, which is an array that contains info like "name", "location", and "products" for a number of stores. "products" is another array within each store, which shows what products each store carries.

I'd like to set the strpos function to search through each store's list of products (which I've set up as an array of strings) to find a certain string (whatever product the user is searching for on the search page), and then those stores will be displayed as search results.

When I try to set this up, I get an error that says strpos was expecting a string and I gave it an array.

Probably a simple fix. Hopefully this makes sense, and any help would be appreciated. Thanks.

Aaron Bini
Aaron Bini
12,129 Points

Added note, I can get the results I want if I set up the list of products as a string rather than an array, like this: "products" => "Soap Toothpaste Cereal Butter"

But I originally had this set up as an array and I'd like to keep it like that if possible. Thanks.

2 Answers

shashank khare
PLUS
shashank khare
Courses Plus Student 472 Points

Something like this ? foreach($haystack as $key => $array) { foreach($array as $value) { if(strpos($value, $needle) !== false) { return $key; } } }

Aaron Bini
Aaron Bini
12,129 Points

Thanks for your response. I changed the function to in_array, which allows searching for $needle string within a $haystack array to achieve desired results. I think I was too tired when I was working on this last night! Thanks.