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 trialLucas Santos
19,315 PointsWhat does the following block of code output?
<?php
$flavors = array("Cake Batter","Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a;
}
?>
I understand foreach loops but im not understanding the $a => $b
part. My guess was Cake Batter but I was wrong.
2 Answers
Jeff Busch
19,287 PointsHi Lucas,
In a foreach loop the variable(s) after as are what is called working variables. In the example you've supplied the variable $a is holding the key and the $b is holding the value as the foreach loops through the array. Since no key has been explicitly assigned php assigns a numeric key and this is what is being echoed out, hence 0 and 1. Remember, if left to php the keys start numbering at zero.
Jeff
Lucas Santos
19,315 Pointsahh ok so "Cake Batter","Cookie Dough" are irrelevant because their just arguments and not a key being assigned to a value. And so when there is no key assigned to a value php numbers them 0, 1 rite
Dan Mirda
3,992 PointsI think if you modified it like it is below you will get it to work. In a for each loop what you usually specify is the array that you will retrieve elements from and a temporary variable. $flavors is the array and $a is the temporary variable that will be assigned the elements in the array.
<?php
$flavors = array("Cake Batter","Cookie Dough");
foreach ($flavors as $a) {
echo $a;
}
?>
Jeff Busch
19,287 PointsJeff Busch
19,287 PointsLucas,
Add echo $b; to your foreach loop and view it.