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 Object-Oriented PHP Basics Building a Collection Shopping List Method

maze
maze
17,027 Points

Better array_key_exists() function??

Hi! I have had troubles using in_array() function in this code.

public function getCombinedIngredients()
    {
        $ingredient_list = array();
        foreach ($this->recipes as $recipe) {
            foreach ($recipe->getIngredients() as $ing) {
                $item = $ing['item'];
                if (strpos($item, ",")) {
                    $item = strstr($item, ",", true);
                }
                if (in_array($item . "s", $ingredient_list)) {
                    $item .= "s";
                } else if (in_array(substr($item, 0 , -1), $ingredient_list)) {
                    $item = substr($item, 0 , -1);
                }
                $ingredient_list[$item] = array($ing["amount"],$ing["measure"]);
            }
        }
        return $ingredient_list;
    }

When you try this

echo Render::listShopping($breakfast->getCombinedIngredients());

everything its ok because there is not a plural item in the breakfast recipes (Onions, Eggs) but when you try the same but with cookbook object

echo Render::listShopping($cookbook->getCombinedIngredients());

you can see the single and plural items (Egg and Eggs, Onion and Onions).

I think it's better to use the array_key_exists() function rather than in_array() because in the code the value to find is a key.

I'm not sure what is the problem with in_array() function because I thought that you use it to check if a neddle value exists in an array but maybe it's checking only a values and not a keys?¿?¿?

maze
maze
17,027 Points

In the next video "Creating a Meal Plan" you can see in the minute 6:51 what I'm talking about (Onion, Onions)

4 Answers

Hamish Payne
Hamish Payne
8,666 Points

Agh that was driving me crazy! Thanks Maze!

This worked for me. Thanks! This was driving me crazy!!!

This solves one portion of my problem, but now it doesn't pluralize the original item. It's returning the singular "Egg" instead of "Eggs" and "Onions" instead of "Onion" etc.