Home  >  Article  >  Backend Development  >  PHP array traversal foreach ($arr as &$value) usage introduction

PHP array traversal foreach ($arr as &$value) usage introduction

WBOY
WBOYOriginal
2016-07-25 08:58:211125browse
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



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn