PHP PHP Arrays and Control Structures PHP Loops While Listing Array Values

edward wong
edward wong
3,349 Points

Help 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
jamesjones21
9,248 Points

the 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
yahya alhalki
1,149 Points

hey but every time i try to change the $key or $value it gives me an error

jamesjones21
jamesjones21
9,248 Points

can you show me your code? I can then see where you are going wrong.