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 trialJustine Lam
8,785 PointsNot understanding foreach and keys
Can someone explain what the correct answer is here?
<?php
$flavors = array("Cake Batter","Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a;
}
?>
1 Answer
Guy Noda-Bailey
18,837 PointsI think it will echo out a list of the keys, ie. [0][1] Let me try it out and get back to you.
Guy Noda-Bailey
18,837 PointsGuy Noda-Bailey
18,837 PointsYep it echoed out the following; 01
In this foreach loop the $a variable is assigned to the Key of the $flavours array! and $b is assigned the Value of that key. Inside the loop it echoes the $a ($flavours Key) each iteration.
thomascawthorn
22,986 Pointsthomascawthorn
22,986 PointsI don't think the array in the question has keys.. Isn't it just a normal single dimension array?
Guy Noda-Bailey
18,837 PointsGuy Noda-Bailey
18,837 PointsYeah, in PHP adding a key is optional, when a key isn't specified PHP will automatically assign the increment of the largest previously used integer key. In this case it will assign what we could think of as the index, as a key.
thomascawthorn
22,986 Pointsthomascawthorn
22,986 Pointsoh of course! Like accessing a single dimensional array by $flavours[n] ! Brain link!