VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-check-foreach-loop-key-value-in-php/

⇱ How to check foreach Loop Key Value in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to check foreach Loop Key Value in PHP ?

Last Updated : 23 Jul, 2025

In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as

Using the for-each loop with simple values

We can use the foreach loop to access and use the elements in an array of simple values, such as strings or numbers.

Example 1: In this example we iterates over the $names array with foreach, printing each name followed by a line break (<br>), resulting in a list of names displayed on separate lines.

Output:

Ramesh
Suresh
Ram
Shyam

In the above example, each element of the array names is iterated over and is assigned to the variable value.

Example 2: In this example we iterates over the $marks array using foreach, printing each mark followed by a line break (<br>), resulting in each mark displayed on a new line.

Output:

45
78
93
69

Using the foreach loop with Key-Value pairs

We will use the same foreach loop to iterate over an array of key-value pairs.

Example : In this case, an array of students and their marks are taken in the array.

Output:

Ramesh - 45
Suresh - 78
Ram - 93
Shyam - 69

In the example above, we iterate over each array element and then extract the key-value pair into variables key and val respectively.

Using array_keys Function to Access Keys and Values

In this new approach, we will use the array_keys function to access the keys directly and then use those keys to access the corresponding values.

Example : In this example we retrieves array keys using array_keys and iterates over them with foreach, printing each key and its corresponding value from the $markSheet array.


Output
Nikunj - 45 
Dhruv - 78 
Yash - 93 
Arti - 69 
 

Using array_walk Function for Iteration

The array_walk function allows you to iterate over the elements of an array, applying a callback function to each element. This method is useful for more complex operations during iteration.

Example: In this example, we use array_walk to iterate over the $markSheet array and print each key-value pair.


Output
Nikunj - 85
Dhruv - 92
Yash - 78
Arti - 88
Comment
Article Tags: