Home > Article > Backend Development > PHP array traversal foreach ($arr as &$value) usage introduction
This article introduces how to use foreach loop to traverse arrays in PHP. Friends in need can refer to it.
Starting from php5, you can add & before $value to modify the elements of the array. This method will assign a value by reference instead of copying a value, which reduces the waste of space and is a good method. Example: <?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 when the array being traversed can be referenced (for example, it is a variable). Example: <?php foreach (array(1, 2, 3, 4) as &$value) { $value = $value * 2; } ?> Detailed reference: http://bbs.it-home.org/shouce/php5/control-structures.foreach.html |