+ 2

What is the purpose of the key variable here?

foreach (array as $key => $value) { code to be executed; }

31st Jan 2017, 12:15 AM
Isaiah Nixon
Isaiah Nixon - avatar
3 Answers
+ 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
31st Jan 2017, 2:46 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 1
Great
7th Feb 2017, 1:37 PM
Souleymane Mouctar Diallo
Souleymane Mouctar Diallo - avatar
+ 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 */
11th Feb 2017, 1:42 PM
Willy