foreach & pit

Example 1.foreach & as different variables (normal result)

<?php
$arr = [11, 22, 33, 44, 55];
foreach ($arr as &$val) {
    $val += 1;
    var_dump($val);
}

echo "#############\n";

foreach ( $arr as $aa) {
    var_dump($aa);
}
$ php test.php 
int(12)
int(23)
int(34)
int(45)
int(56)
#############
int(12)
int(23)
int(34)
int(45)
int(56)

Example 2.foreach & as variable as (undesirable results)

<?php
$arr = [11, 22, 33, 44, 55];
foreach ($arr as &$val) {
    $val += 1;
    var_dump($val);
}

echo "#############\n";

foreach ($arr as $val) {
    var_dump($val);
}

Results of the:

$ php test.php 
int(12)
int(23)
int(34)
int(45)
int(56)
#############
int(12)
int(23)
int(34)
int(45)
int(45)
<?php
$arr = [11, 22, 33, 44, 55];
foreach ($arr as &$val) {
    $val += 1;
    var_dump($val);
}

echo "#############\n";

foreach ($arr as $val) {
    var_dump($val);
}

Results of the:

$ php test.php 
int(12)
int(23)
int(34)
int(45)
int(56)
#############
int(12)
int(23)
int(34)
int(45)
int(45)

Example 3.foreach & as & variables as (a desired result)

<?php
$arr = [11, 22, 33, 44, 55];
foreach ($arr as &$val) {
    $val += 1;
    var_dump($val);
}在这里插入代码片

echo "#############\n";

foreach ($arr as &$val) {
    var_dump($val);
}

Results of the:

$ php test.php 
int(12)
int(23)
int(34)
int(45)
int(56)
#############
int(12)
int(23)
int(34)
int(45)
int(56)

explain

Example 1, the desired result is normal, much explanation.
Example 2, after the first pass foreach, $ val pointed to the space $ arr [ '4']; when re-circulated, corresponding to the following procedure:

$val = $arr['4'] = $arr['0'] = 12;
$val = $arr['4'] = $arr['1'] = 23;
$val = $arr['4'] = $arr['2'] = 34;
$val = $arr['4'] = $arr['3'] = 45; //(关键步骤)
$val = $arr['4'] = $arr['4'] = 45;

Example 3, after the first pass foreach, $ val pointed to the space $ arr [ '4']; when re-circulated, & $ val corresponding to a new space, and therefore the problem of coverage does not occur.

Published 236 original articles · won praise 145 · views 440 000 +

Guess you like

Origin blog.csdn.net/u011944141/article/details/102902621