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 trialKelvin Zhao
10,418 PointsUsing =>
What exactly does => mean in the foreach loop?
Does
foreach(xxx as yyy => zzz)
and
foreach(xxx as zzz => yyy)
mean the same thing? If not, how do we determine the hierarchy and usage of => to get the right loop?
2 Answers
Stone Preston
42,016 Pointsthat syntax is for accessing the keys in addition to the values of an associative array.
foreach ($array as $key => $value)
that will allow you to access both the value and the key of the array within the loop body
for example if I had an associative array called people with id numbers as the keys and names as the values and I wanted to loop through that array I would use:
foreach ($people as $id => $name) {
echo $id . " is the key";
echo $name . " is the value";
}
mikes02
Courses Plus Student 16,968 Pointsthe $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2. For example, you could do an associative array like:
$car = array('brand' => 'toyota', 'model' => 'camry', 'color' => 'blue', 'year' => '2014');
Where you establish key => value pairs. So in your loop you could do:
foreach($car as $key => $value)
{
echo '<p>'.$key.' - '.$value.'</p>';
}
Kelvin Zhao
10,418 PointsThanks!!! =)
Konrad Pilch
2,435 PointsIts the same as this rigth?
$products = array();
$products[101] = array(
"name" => "Logo Shirt, Red",
"img" => "img/shirts/shirt-101.jpg",
"price" => 18,
"paypal" => "9P7DLECFD4LKE"
);
$products[102] = array(
"name" => "Mike the Frog Shirt, Black",
"img" => "img/shirts/shirt-102.jpg",
"price" => 20
);
Kelvin Zhao
10,418 PointsKelvin Zhao
10,418 PointsIcic. Thanks!