PHP Tutorial Tutorials - PHP foreach Loop

PHP foreach Loop

The foreach loop in PHP provides an easy way to iterate over arrays.

Syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

For example:

<?php
$arr = array(6,7,8,9);
 
// iterate over the array
foreach($arr as $value){
    echo $value . "<br>";
}

foreach($arr as $key => $val){
    echo "key=".$key.", value=".$val . "<br>";
}
?>

Output:

6
7
8
9
key=0, value=6
key=1, value=7
key=2, value=8
key=3, value=9

Notes:
Reference of a $value and the last array element remain even after the foreach loop.
It is recommended to destroy it by unset().

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// unset($value); // break the reference with the last element

var_dump($arr); // array(2, 4, 6, &int(8))
$value = 10;
var_dump($arr); // array(2, 4, 6, &int(10))
unset($value);
var_dump($arr); // array(2, 4, 6, 10)
?> 
Date:2019-10-01 02:38:25 From:www.Lautturi.com author:Lautturi