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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-25 08:58:21
Original
1180 people have browsed it
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)
?>
Copy after login

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;
}
?>
Copy after login

Detailed reference: http://bbs.it-home.org/shouce/php5/control-structures.foreach.html



Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template