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 trialThomas Grow
3,238 PointsDisconnect about =>
I keep messing up on questions such as this:
What does the following block of code output?
<?php
$flavors = array("Cake Batter","Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a;
}
?>
I know that $a is the key and $b is the value... but I'm having trouble distinguishing the difference. After all, what else can $a be? I thought that the answer for this would be: Cake BatterCookie Dough , but that's apparently wrong. Would the answer be 01???I just don't understand. Can someone clear up the whole => thing for me? On the surface, it seems easy... but I'm just not getting it.
Thanks.
3 Answers
Nicklas Wiborg
12,692 PointsIn the foreach loop you can assign the key of the looped element to a variable trough =>.
In your case you loop trough two elements in the array positions 0 and 1.
When the foreach-loop goes the first time it will assign $b to get the value "Cake Batter" and $a the key of the element which is 0. In the next element it will assign $b = "Cookie Dough" and $a = 1;
So the answer of your question is: 01
Carles Jove i Buxeda
4,281 PointsNicklas Wiborg's answer is right. I'd just add that it outputs 0 and 1 because, since they don't have a specific key, they are integers by default.
Other examples would be:
<?php
$flavors = array( 4 => "Cake Batter", 7 => "Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a; // outputs 4 and 7
}
$flavors = array( 'cool' => "Cake Batter", 'cooler' => "Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a; // outputs cool and cooler
}
?>
Here's the Array page from the PHP docs
Thomas Grow
3,238 PointsThanks Nicklas Wiborg, Carles Jove i Buxeda