Friday, October 10, 2025
HomeLanguagesHow to check foreach Loop Key Value in PHP ?

How to check foreach Loop Key Value in PHP ?

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

  1. To loop through a list of simple values.
  2. To loop through a list of key-value pairs.

Using the foreach 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:

PHP




<?php
    $names = array("Ramesh", "Suresh", "Ram", "Shyam");
    foreach ($names as $value) {
    echo "$value <br>";
    }
?>


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:

PHP




<?php
    $marks = array(45, 78, 93, 69);
    foreach ($marks as $value) {
      echo "$value <br>";
    }
?>


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 3: In this case, an array of students and their marks are taken in the array.

PHP




<?php
    $markSheet = array("Ramesh"=>45, "Suresh"=>78, "Ram"=>93, "Shyam"=>69);
    foreach ($markSheet as $key => $val) {
      echo "$key - $val<br>";
    }
?>


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.

RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS