php foreach循环引用的问题

使用代码   在嵌套使用循环的时候 要注意循环引用的问题

demo 

$arr = [
            'a', 'b',
            'c', 'd',
        ];
        foreach ($arr as &$each){
            var_dump($arr);
        }
        foreach ($arr as $each){
            var_dump($arr);
        }

  

输出结果

 

array(4) {
  [
    0
  ]=>
  &string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  string(1) "d"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  &string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  string(1) "d"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  &string(1) "c"
  [
    3
  ]=>
  string(1) "d"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  &string(1) "d"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  &string(1) "a"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  &string(1) "b"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  &string(1) "c"
}
array(4) {
  [
    0
  ]=>
  string(1) "a"
  [
    1
  ]=>
  string(1) "b"
  [
    2
  ]=>
  string(1) "c"
  [
    3
  ]=>
  &string(1) "c"
}

 

原因 是

php的foreach会在每次循环时,讲当前元素赋值给each, 然后进入循环体

当foreach遍历完成后, each变量没有释放而是指向了arr数组中的最后一个元素, 所以在后面给each赋值时, 其实改变的时arr数组的最后一个元素  所以最后一个一直在引用赋值

 

posted @ 2020-02-21 16:06  做人如水,做事如山  阅读(701)  评论(0编辑  收藏  举报