Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.