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 trialahmed saleh
2,754 Pointswhat does the variable after (AS) keyword in foreach contain?
here is my question
$myarray = array("a");
foreach($myarray as $con ){
echo $con;
}
my question is , does $con = a
or $con = $myarray[0]
?
maybe some will say why is this question .. well because in nested lesson i saw like this $con["myvar"]
, instead of $con[0]["myvar"]
thank you
2 Answers
Erik McClintock
45,783 PointsAhmed,
(I have edited your post to use Markdown to display your code correctly)
In that instance of a foreach loop, the value of $con
will be the value held at each index of the array, so for that array that only has one item in it, the value will be "a".
To help illustrate this further, let's say you had the following code:
$myColors = array(
'red',
'orange',
'blue'
);
foreach ( $myColors as $color ) {
echo $color . " ";
}
This would iterate through each item in the $myColors array, and print out its value. So, this would echo "red orange blue".
Erik
ahmed saleh
2,754 Pointsnvm , thank you anyway
ahmed saleh
2,754 Pointsahmed saleh
2,754 Pointsfirst L thank you a lot for your replay , but my question was what is thing inside ($color) variable now is it red ,orange etc or $color[0],$color[1] etc .. i want to know because if we made array like this $myColors[0] = array("favcolor"=>"red"); if we want to access it we need $myColors[0]["favcolor"] as you know , but if we did 0["favcolor"] ... so i'am confused , does't send the value directly to $color OR send array with index . thank you
Erik McClintock
45,783 PointsErik McClintock
45,783 PointsAhmed,
As I mentioned, the $con (or $colors, from my example) variable holds a reference to the value stored at each index in the given array. In the example you gave initially, with an array that had only one value in it (of "a"), the value thus of $con would be "a". Setting up a foreach in that manner will simply output the values at each index of the array.
I apologize, but I'm not sure if there is something else that you're asking; it seems you're asking what is stored in the $con variable...is there something else you're wondering about?
Erik