Different ways of foreach PHP and why you should use it?

foreach loop

There are different type of loops in PHP which includes for loop, while loop, do-while loop, and foreach loop. But which one to select when writing an actual code? Well, it all depends on your requirements and sometimes your personal preferences. I like Foreach Loop the most for a couple of reasons:

  1. it can handle multi-dimensional arrays very easily
  2. It’s syntax is very simple
  3. It can take down complex array structures
  4. it can handle objects as well
  5. it is better in performance as compared to other loops in php

The basic syntax of the foreach loop is below:

foreach (iterable_expression as $value)
    statement
foreach (iterable_expression as $key => $value)
    statement

Simple Right!

First, we start with simple arrays just to make sure that you completely understand what is going in a foreach loop

Let’s declare a simple PHP array.

Foreach Example # 1:

<?php
// declare a single dimensional array
$arr = array("apple", "mango", "banana", "cherry");
foreach ( $arr as $value ){
   echo "Fruite Name: ".$value." <br>";
}

// The output will be this
// Fruite Name: apple
// Fruite Name: mango
// Fruite Name: banana
// Fruite Name: cherry

The above example was with the single-dimensional array. Let me show you an example with key-value pair.

Foreach Example # 2:

<?php
$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

// $k will return the index of array
// $v is returning the value

Let’s show you the nested array

Example # 3:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>
OUTPUT:
A: 1; B: 2
A: 3; B: 4

<?php
// you can also provide a single element in list(), in that case the leftover array values will be ignored:
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a)) {
    // Note that there is no $b here.
    echo "$a\n";
}

// OUTPUT
// 1
// 3

You can also “break” the control structure to exit from the “foreach” loop. Let me show you the example below:

Example # 4

<?php

$array = [ 'one', 'two', 'three', 'four', 'five' ];

foreach( $array as $value ){
    if( $value == 'three' ){
        echo "Number three was found!";
        break;
    }
}

?>

I hope that will help you understand how the foreach loop is working in PHP.

Happy coding