Categories
PHP Programming Language

PHP foreach

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

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

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.

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *