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
Joel David Crouse
9,062 Pointsstripos isn't working correctly...
The problem I am having is that instead of display only the matching products, It is showing every product in the products array. Why isn't it just showing the product(s) that match the search query?
Here's my function that is suppose to only return products that match the search term:
function get_products_q($q) {
$results = array();
$full_cat = get_catalog();
foreach ($full_cat as $product) {
if (stripos($product["name"],$q) !== false) {
$results[] = $product;
}
}
return $results;
}
Here's my controller code for the search:
$q_term = "";
if (isset($_GET["q"])) {
$q_term = trim($_GET["q"]);
if ($q_term != "") {
$matching_products = get_products_q($q_term);
}
}
And finally my view code
if ($q_term != "") {
if (!empty($matching_products)) {
$list_view_html = "";
foreach ($products as $product) {
$list_view_html = $list_view_html . get_list_view_html($product);
}
echo $list_view_html;
} else {
echo '<p>No products found.</p>';
}
}
What am I doing wrong?
Thanks in advance.
2 Answers
Jason Anello
Courses Plus Student 94,610 PointsIn your view code you're checking if the $matching_products array is not empty but then looping through the $products array.
Shouldn't you be using $matching_products in the loop?
Joel David Crouse
9,062 PointsYes, you are right! Thanks a million Jason :)