PHP 8.5 foreach Loop Function with Example

The PHP 8.5 foreach loop works exactly the same as in previous versions. No new syntax was introduced in PHP 8.5 for loops. It is the best loop for iterating through arrays and objects.

What is a foreach Loop in PHP 8.5?

A foreach loop is used to loop through each element of an array or object. It automatically moves to the next element without needing a counter or condition.

Basic Syntax

foreach ($array as $value) {
// Code to execute
}

With key and value:

foreach ($array as $key => $value) {
// Code to execute
}

Basic Example 1: Loop Through an Array

<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>

Output:

Apple
Banana
Mango
Orange

How it works?

$fruits is the array
$fruit holds each value one by one
Loop runs automatically until all elements are done

Example 2: With Key and Value

<?php
$ages = [
"John" => 25,
"Smith" => 30,
"Kalle" => 22
];
foreach ($ages as $name => $age) {
echo "$name is $age years old<br>";
}
?>

Output:

John is 25 years old
Smith is 30 years old
Kalle is 22 years old

Example 3: Numeric Index with Key

<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $index => $color) {
echo "Index $index: $color<br>";
}
?>

Output:

Index 0: Red
Index 1: Green
Index 2: Blue

Example 4: Loop Through an Object

<?php
class Student {
public $name = "John";
public $age = 20;
public $city = "Delhi";
}
$student = new Student();
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
?>

Output:

name: John
age: 20
city: Delhi