+ 2
What is the purpose of the key variable here?
foreach (array as $key => $value) { code to be executed; }
3 Respostas
+ 2
Foreach only use for array, and key variable is input array index. Like
$arr = array(8,6,4);
echo $arr[0];
It will echo 8. Which is array value and 0 is its key. Hope it helps you
+ 1
Great
+ 1
Using $key variable is also useful with mutlidimensional array sorting.
// Multidimensional associative array for learning purposes
$multiarr = array(
"Fruits" => array("Apples", "Pears", "Bananas", "Oranges"),
"Cars" => array("BMW", "VW", "Toyota", "Audi"),
"Cities" => array("New York", "London", "Toronto", "Sydney")
);
// Looping through $multiarr which is a multidimensional array
foreach($multiarr as $key => $subarrays) {
// !!Printing $subarrays will produce error since $subarrays are arrays and not string!!
// We are printing the keys to use as headers. Keys can be associative or numeric
echo "<h3>" . $key . "</h3>";
// Now we need to loop through arrays inside $multiarr to print out data.
// No need for $key unless you need specific numeric info for further code
foreach ($subarrays as $data) {
echo $data . "<br>";
}
}
/* OUTPUT:
Fruits:
Apples
Pears
Bananas
Oranges
Cars
BMW
VW
Toyota
Audi
Cities
New York
London
Toronto
Sydney
*/