Foreach Loop in PHP

Share this post on:

Foreach loop in PHP is a type of loop that is used to iterate over arrays and objects. This loop allows you to loop through each element of an array or object and execute a block of code for each element. In this blog post, we will explore the foreach loop in PHP and provide examples to demonstrate its usage.

Syntax of the foreach loop

The syntax of the foreach loop in PHP is as follows:

foreach($array as $value) {
  // block of code to be executed
}

Let’s examine each part of the foreach loop syntax in detail:

  • $array: This is the array or object that you want to loop through.
  • $value: This is a variable that will hold the value of the current element in the array or object.
  • Block of code: This is the code that is executed for each element in the array or object.

Example 1: Looping through an array

Let’s start with a simple example that demonstrates how to use the foreach loop to loop through an array:

$fruits = array("apple", "banana", "cherry", "date");

foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}

In this example, we create an array of fruits and then use the foreach loop to loop through each element of the array. The $fruit variable holds the value of the current element in the array, and we use the echo statement to print each fruit on a new line.

The output of this code is:

apple
banana
cherry
date

Example 2: Looping through an object

Let’s take another example that demonstrates how to use the foreach loop to loop through an object:

class Person {
  public $name;
  public $age;
  public $gender;
}

$person = new Person();
$person->name = "John";
$person->age = 30;
$person->gender = "Male";

foreach ($person as $key => $value) {
  echo $key . ": " . $value . "<br>";
}

In this example, we create a Person object and set its properties. We then use the foreach loop to loop through each property of the object. The $key variable holds the name of the current property, and the $value variable holds the value of the current property. We use the echo statement to print the name and value of each property on a new line.

The output of this code is:

name: John
age: 30
gender: Male

Conclusion

The foreach loop is a powerful construct that allows you to loop through arrays and objects in PHP. This loop is particularly useful when you need to perform a specific action for each element in an array or object. By mastering the foreach loop, you can write more efficient and effective PHP code.

Share this post on:

Leave a Reply