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

New Algorithm for PHP Search!

I Just finished this at about 2 in the morning. Been trying to code an algorithm to search an array for a size ie: if a person searches "Large" it will show all the large shirts and if you add something to the array like "XX-Large" then if they search of "XX-Large" it will come up! May not sound much but it was quite difficult to come up without going to places like Stackoverflow and looking for answers!

Code it here: (Just modify your get product search function and it should work)

function get_products_search($s){
    $results = array();
    $all = get_products_all();


    foreach($all as $product){
        if (stripos($product["name"], $s) !== false || $product["sku"] == $s){
            $results[] = $product;
        }    

        foreach($all[$product["sku"]]["sizes"] as $size){
            if(stripos($size, $s) !== false){
                $results[] = $product;
            }
        }
    }

    return $results;
}

Please leave feedback in the comments!

Robert Bojor
Robert Bojor
Courses Plus Student 29,439 Points

You might consider using $results[$product['sku']] = $product when you add your product array to the search results. This way if both conditions hit you will have a results array containing unique products.

Hey Robert

I am not sure why I should use php $results[$product['sku']] = $product; instead of php $results[] = $product Because the conditions will never meet due to when I search for 101 it will return the product with a SKU of 101 but if I search for 101 Large it won't return anything so the conditions will never meet?

Robert Bojor
Robert Bojor
Courses Plus Student 29,439 Points

It's so easy to code for the perfect conditions and I wish you only perfect clients and websites. Unfortunately when the clients start using their websites they realise it's not that easy to run an online shop and there's actual work involved so they start cutting corners where they can.

Adding a bit of extra code to save you trouble down the road will only help and can't hurt :)

The trick I've mentioned it will ensure you always have unique results, something that is desired on a search results page.

1 Answer

Thank you so much!

Literally after reading your first comment I found a bug and solved it with your input!

Cheers!