Discussion :php USES foreach of $arr as $value in foreach

  • 2020-06-19 09:55:43
  • OfStack

Starting with PHP 5, this can be easily passed by adding before $value & To modify the elements of the array. This method assigns a value by reference instead of copying a value.

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

This method is only available if the traversed array can be referenced (for example, a variable).

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

Related articles: