• Home
  • How does PHP ‘foreach’ actually work?

How does PHP ‘foreach’ actually work?

The foreach loop in PHP allows you to iterate over the elements of an array or object and perform a block of code on each element. It is a convenient way to access and manipulate the elements of an array or object, and is often used to process data or display lists.

The foreach loop has the following syntax:

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

or

foreach (array as $key => $value) {
// code to be executed
}

The array in the foreach statement is the array or object to be iterated over. The $value variable is a placeholder for the current element, and the optional $key variable is a placeholder for the current element’s key.

The foreach loop will iterate over each element of the array, assigning the value of the element to the $value variable and the key of the element to the $key variable (if specified). It will then execute the code block once for each element.

Here is an example of a foreach loop that iterates over an array and prints the elements:

$array = array(1, 2, 3, 4, 5);
foreach ($array as $value) {
echo $value . "\n";
}

This will output the following:

1
2
3
4
5

You can also use the foreach loop to iterate over the properties of an object, like this:

$object = (object) array('a' => 1, 'b' => 2, 'c' => 3);
foreach ($object as $key => $value) {
echo $key . ": " . $value . "\n";
}

This will output the following:

a: 1
b: 2
c: 3

The foreach loop is a convenient and efficient way to access and manipulate the elements of an array or object.