Change language

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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method