PHP PHP Arrays and Control Structures PHP Loops Looping with PHP

Question about the foreach loop.

Hi. I just want to make sure that i fully understand what's going on :]

we have this multi-dimensional array:

$flavors = array();
$flavors[] = array("name" => "Cookie Dough",      "in_stock" => true);
$flavors[] = array("name" => "Vanilla",           "in_stock" => false);
$flavors[] = array("name" => "Avocado Chocolate", "in_stock" => false);
$flavors[] = array("name" => "Bacon Me Crazy",    "in_stock" => true);
$flavors[] = array("name" => "Strawberry",        "in_stock" => false);

in order to loop through the multi-dimensional array we use the foreach loop.

my question is about this code:

foreach($flavors as $flavor) {
    echo $flavor["name"];

$flavor in the foreach loop represent the "values" of each key, for example in the $flavors array,in the first array iteration $flavor represent "Cookie Dough" but why we have to add the key of the value which is "name" >>> $flavor["name"] in order to access the value? WE do it because we have another key-value pair? and in that way we can differ between them?

thanks in advance!

2 Answers

Steven Parker
Steven Parker
195,561 Points

Each element of the "$flavors" array is another array, so the "$flavor" represents the entire smaller array which has multiple key/value pairs in it.

So the key is used with "$flavor" to select a specific value associated with that key. And yes, you were right about that part.