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 trialJason Glass
6,456 PointsHelp me understand this process..
For some reason this is like looking at a math problem that is over my head..
<?php
$flavors = array("Cake Batter","Cookie Dough");
foreach ($flavors as $a => $b) {
echo $a;
}
?>
..naturally I can run the code and see the outcome is "01", but why "01"?
2 Answers
Jayden Spring
8,625 PointsSimply think of it as this:
foreach($array as $key => $value)
{
....code...
}
You are iterating through each element in the array ($flavours) and saying that $a is the variable for the key and $b is the variable for the value. However given your array this would not work as you are using a simple array not an associative one (key value pairs).
For you're array you simply need
foreach($flavours as $flavour)
{
echo $flavour
}
If you had an array
$flavours = array(
1 => 'Caramel',
2 => 'Strawberry'
);
You could use the key value interation
William Li
Courses Plus Student 26,868 PointsHello, Jason Glass A very detailed explanation of this question has been provided at this post https://teamtreehouse.com/forum/help-me-understand-the-difference-between-the-following-codes-in-php, Please check it out.
Hope it helps, don't hesitate to ask if you have further question.
Jason Glass
6,456 PointsJason Glass
6,456 PointsWell that was kind of part of my confusion.. This was copied from a multi-choice code challenge.
Jayden Spring
8,625 PointsJayden Spring
8,625 PointsBest way to understand it is if you use the => in the foreach you are going to be retrieving two values, a key and value. Even if you have a key value pair array (associative array) if you just did $array as $item it would just return the item. If you have a look at PHP's manual here (http://php.net/manual/en/language.types.array.php) it explains it all pretty well