PHP foreach() loop for indexed and associative arrays

In this tutorial, we look at the PHP foreach() loop. We also look at how to use it while working with an indexed or associative array.

Table of Contents - PHP foreach:

  • What is foreach()?
  • Code and Explanation
  • Indexed arrays
  • Associative arrays
  • Closing thoughts

What is foreach in PHP?

The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

Syntax of PHP foreach():

The foreach() method has two syntaxes, one for each type of array.

The syntax for indexed arrays is as given in the following code block:

foreach (iterable as $value)

The syntax for associative arrays:

foreach (iterable as $key => $value)

Here, “Iterable” is the required parameter. It is the array or the variable containing the array. “$value” is a variable that stores the current element in each iteration.

Associated array, uses keys and values, and hence the $key & $values in the second syntax represent the same accordingly.

Code & Explanation:

In this section, we first look at how the foreach() function works on an indexed array followed by which we look at it’s working on an associative array.

PHP Foreach() on Indexed arrays:

$flexiple = array("Hire", "top", "freelance", "developers");

foreach ($flexiple as $value) {
  echo "$value <br>";

The output of the above code snippet would be:


PHP Foreach() on an Associative array:

$freelancer = array( 
    "name" => "Eric", 
    "email" => "[email protected]", 
    "age" => 22, 
    "gender" => "male"
// Loop through employee array 
foreach($freelancer as $key => $value) { 
    echo $key . ": " . $value . "<br>"; 

The output of the above code snippet would be:

name: Eric
email: [email protected]
age: 22
gender: male

Now let’s look at a case where we pass a second argument.

As you can see the key and the values of the associative array were printed. Additionally, we replaced “=>” with a “:” to make it more readable.

Closing thoughts:

The foreach() method would return an error in case you use it on variables with a different data type. Additionally, the foreach() method does not modify the values of the internal pointer.

Once you have understood the working to the foreach() method try working with the for loop.