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

Quiz question

This has me puzzled.

Can someone walk me through this?

                <?php

                  $flavors = array("Cake Batter","Cookie Dough");

                     foreach ($flavors as $a => $b) {

                     echo $a;

                     }

Answer is 01 but where that comes from I don't get.

M

?>

3 Answers

Hi Morrice!

If I'm correct, calling your 'foreach' loop like that is outputting the keys for the items in the $flavors array. Keys in arrays identify the strings associated with them. Each item has its own key, starting with 0- so "Cake Batter" has a key of 0, and "Cookie Dough" has a key of 1. By echoing the $a value, you're echoing the key of the array items. (where, in your foreach loop, $a is the key of the array item and $b is the string associated with that key) Since there are only two keys in that array, 0 and 1; they will both be echoed out. If your foreach loop looked like this:

<?php
$flavors = array("Cake Batter","Cookie Dough");

foreach ($flavors as $a => $b) {
    echo $b;
}
?>

Then your output would be Cake BatterCookieDough.

Hope this helps!

The correct answer is for echo $b would actually be "Cake Batter." I didn't get it either, had to go through all options before I understood it wants the string of the FIRST array item only.

<?php $flavors = array("Cake Batter","Cookie Dough"); foreach ($flavors as $a => $b) { echo $b; exit; } ?>

$flavors = array("Cake Batter","Cookie Dough") creates an array with a default key 0 that auto increment itself.

echo $a display the key, so 0 for "Cake Batter" and 1 for "Cookie Dough".

Thanks guys

You put me on the right path