+

How do I find the index of a foreach loop in PHP?

Syntax:
foreach ($array as $element) {// PHP Code to be executed} 
or
 foreach ($array as $key = > > $element) {// PHP Code to be executed} 
Returned values:
  • $key:this variable contains the index of the key of the current element /
  • $value: oneach iteration, the current value of the array element is assigned to the variable $value.
Program 1:  
// Declare the array $arr = array (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  
// Iterate over the array using foreach
// create and store the key and its value 
// Use a foreach loop to display
// allele key foreach ( $arr as $key = > $value ) { echo "key =" . $key . ", value =" . $value . "" ; }  
?>
Output:
key = 0, value = 1 key = 1, value = 2 key = 2, value = 3 key = 3, value = 4 key = 4, value = 5 key = 5, value = 6 key = 6, value = 7 key = 7, value = 8 key = 8, value = 9 key = 9, value = 10 
Program 2:  
/ / Declare array $arr = array ( "a" = > "Welcome" , "b" = > " to " , " d " = > "GeeksforGeeks");  
// Iterate over the array using foreach
// create and store the key and its value 
// Use a foreach loop to display
// allele key foreach ( $arr as $key = > $value ) { echo "key =" . $key . ", value =" . $value . "" ; }  
?>
Output:
key = a, value = 1 key = b, value = 2 key = c, value = 3 key = d, value = 4 
Program 3:  
// Declare a multidimensional array $arr = array ( array (1, 2, 3), array (4, 5, 6), array (7, 8, 9) ) ;  
// Iterate over the array using foreach
// create and store the key and its value 
// Use a foreach loop to display
// allele key foreach ( $arr as $keyOut = > $out ) { foreach ( $out as $keyIn = > $value ) { echo "key = (" . $keyOut . "," . $keyIn . "), value =" . $value . "" ; } }  
?>
Output:
key = (0, 0), value = 1 key = (0, 1), value = 2 key = (0, 2), value = 3 key = (1, 0), value = 4 key = (1, 1), value = 5 key = (1, 2), value = 6 key = (2, 0), value = 7 key = (2, 1), value = 8 key = (2, 2), value = 9 
Get Solution for free from DataCamp guru