PHP For and For-each Loop

In PHP, the foreach loop is a handy way to iterate over arrays and objects. It allows you to loop through each element of an array or object without needing to manage the loop counter manually. Here's a basic guide to using foreach in PHP:

Syntax

Iterating over an Array


1. Basic Syntax:

php
$array = ['apple', 'banana', 'cherry'];
foreach ($array as $value) {
    echo $value . "\n";
}


In this example, $value will take on each value of the $array in turn, and you can use it inside the loop body.

2. Key-Value Pairs:

php
    $array = [
        'first' => 'apple',
        'second' => 'banana',
        'third' => 'cherry'
    ];
    foreach ($array as $key => $value) {
        echo $key . ' => ' . $value . "\n";
    }


    Here, $key will take on each key from the array, and $value will take on the corresponding value.

Iterating over an Object


1. Basic Syntax:

    php
    class Fruit {
        public $name;
        public $color;
        public function __construct($name, $color) {
            $this->name = $name;
            $this->color = $color;
        }
    }
    $fruits = [
        new Fruit('apple', 'red'),
        new Fruit('banana', 'yellow'),
        new Fruit('cherry', 'red')
    ];
    foreach ($fruits as $fruit) {
        echo $fruit->name . ' is ' . $fruit->color . "\n";
    }


    In this case, $fruit represents each object in the $fruits array, and you can access its properties.

Examples


1.  Array of Numbers:

php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
    echo $number * $number . "\n"; // Outputs squares of numbers
}

2. Associative Array:
php
    $person = [
        'name' => 'John',
        'age' => 30,
        'city' => 'New York'
    ];
    foreach ($person as $key => $value) {
        echo $key . ': ' . $value . "\n";
    }


Notes


Reference Handling: If you need to modify the original array or object elements within the loop, you can use a reference:

php
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as &$number) {
    $number *= 2; // Modifies the array elements
}
print_r($numbers); // Output: [2, 4, 6, 8, 10]


Remember to unset the reference after the loop to avoid unintended behavior:

php
    unset($number);


Objects with Traversable Interface: If you are iterating over an object that implements the Traversable interface, such as classes implementing Iterator or IteratorAggregate, foreach will work similarly to how it does with arrays.

Using foreach is a powerful way to simplify your code when working with collections in PHP, making it cleaner and easier to understand.




  • To Share this Link, Choose your plateform


Our Other Tutorials