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 trialedward wong
3,349 PointsHelp with understanding this video
Three questions I have:
1) Inside the list's parameter, how come the $key and $val variables didn't have to be declared first before using them?
2) When echoing out the $key and $val variables, why are they both within double quotes? I thought it would've been written as echo $key . " => " . $val?
3) Is the whole point of looping through an array is to be able to echo out individual items contained in the array?
2 Answers
jamesjones21
9,260 Pointsthe foreach loop is great for working with arrays:
//The $key and $value variables can be named anything, for which ever suits your requirement, but as for beginners to understand they use $key to assign the array key to that variable and $value to assign the value to it.
// The variables are set within the foreach loop, so its within the scope of the loop, if used outside of the loop tags then they will be undefined variables.
//$key = the array keys
//$value = the value stored within the key
foreach($array as $key => $value){
//code to execute
}
Hopefully this sums up everything and if you need me to provide more information, please do let me know. Kind regards, James
yahya alhalki
1,149 Pointshey but every time i try to change the $key or $value it gives me an error
jamesjones21
9,260 Pointscan you show me your code? I can then see where you are going wrong.