foreach
PHP Manual
PHP Manual»Strutture di controllo»foreach

(PHP 4, PHP 5, PHP 7, PHP 8)

The foreach construct provides an easy way to iterate over arrays and Traversable objects. foreach will issue an error when used with a variable containing a different data type or with an uninitialized variable.

foreach can optionally get the key of each element:

foreach (iterable_expression as $value) {
    statement_list
}

foreach (iterable_expression as $key => $value) {
    statement_list
}

The first form traverses the iterable given by iterable_expression. On each iteration, the value of the current element is assigned to $value.

The second form will additionally assign the current element's key to the $key variable on each iteration.

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key().

It is possible to customize object iteration.

Example #1 Common foreach usages

<?php

echo "Value only\n";
$array = [1, 2, 3, 17];

foreach ($array as $value) {
    echo "Current element of \$array: $value.\n";
}

echo "\n\nKey and value:\n";
$array = [
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
];

foreach ($array as $key => $value) {
    echo "Key: $key => Value: $value\n";
}

echo "\n\nMulti-dimensional key-value arrays:\n";
$grid = [];
$grid[0][0] = "a";
$grid[0][1] = "b";
$grid[1][0] = "y";
$grid[1][1] = "z";

foreach ($grid as $y => $row) {
    foreach ($row as $x => $value) {
        echo "Value at position x=$x and y=$y: $value\n";
    }
}

echo "\n\nDynamic arrays:\n";
foreach (range(1, 5) as $value) {
    echo "$value\n";
}

Il precedente esempio visualizzerà:

Value only
Current element of $array: 1.
Current element of $array: 2.
Current element of $array: 3.
Current element of $array: 17.


Key and value:
Key: one => Value: 1
Key: two => Value: 2
Key: three => Value: 3
Key: seventeen => Value: 17


Multi-dimensional key-value arrays:
Value at position x=0 and y=0: a
Value at position x=1 and y=0: b
Value at position x=0 and y=1: y
Value at position x=1 and y=1: z


Dynamic arrays:
1
2
3
4
5

Nota:

foreach does not support the ability to suppress error messages using the @.

Unpacking nested arrays

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

It is possible to iterate over an array of arrays and unpack the nested array into loop variables by using either array destructuring via [] or by using the list() language construct as the value.

Nota: Please note that array destructuring via [] is only possible as of PHP 7.1.0.

In both of the following examples $a will be set to the first element of the nested array and $b will contain the second element:

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

foreach ($array as [$a, $b]) {
    echo "A: $a; B: $b\n";
}

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b\n";
}

Il precedente esempio visualizzerà:

A: 1; B: 2
A: 3; B: 4
A: 1; B: 2
A: 3; B: 4

When providing fewer variables than there are elements in the array, the remaining elements will be ignored. Similarly, elements can be skipped over by using a comma:

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

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

foreach ($array as [, , $c]) {
    // Skipping over $a and $b
    echo "$c\n";
}

Il precedente esempio visualizzerà:

1 2
3 4
5
6

A notice will be generated if there aren't enough array elements to fill the list():

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

foreach ($array as [$a, $b, $c]) {
    echo "A: $a; B: $b; C: $c\n";
}

Il precedente esempio visualizzerà:

Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:

foreach and references

It is possible to directly modify array elements within a loop by preceding $value with &. In that case the value will be assigned by reference.

<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now [2, 4, 6, 8]
var_dump($arr);
unset($value); // break the reference with the last element

Il precedente esempio visualizzerà:

array(4) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  &int(8)
}

Avviso

A reference to the $value of the last array element remains even after the foreach loop. It is recommended to destroy it using unset(). Otherwise, the following behavior will occur:

<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now [2, 4, 6, 8]
var_dump($arr);

// without an unset($value), $value is still a reference to the last item: $arr[3]

echo "\nAnother loop:\n";
foreach ($arr as $key => $value) {
    // $arr[3] will be updated with each value from $arr...
    echo "{$key} => {$value}\n";
}
// ...until ultimately the second-to-last value is copied onto the last value
var_dump($arr);

Il precedente esempio visualizzerà:

array(4) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  &int(8)
}

Another loop:
0 => 2
1 => 4
2 => 6
3 => 6
array(4) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  &int(6)
}

Example #2 Iterate a constant array's values by reference

<?php
foreach ([1, 2, 3, 4] as &$value) {
    $value = $value * 2;
    echo $value . "\n";
}

Il precedente esempio visualizzerà:

2
4
6
8
To Top