【问题标题】:php unset not working in foreach for arrayphp unset 在 foreach 中对数组不起作用
【发布时间】:2019-11-27 07:14:57
【问题描述】:

服务器nginx+php-fpm php 7.2

我试过http://sandbox.onlinephpfunctions.com/code/200d19b2663ee01391b9d0a1745ab677b3f219df

$accounts = [
    0 => [
        "active" => true    
    ],
    1 => [
        "active" => false    
    ]
];

foreach($accounts as &$value) {

    if($value['active'] === false) {
         var_dump($value);
         unset($value);
    }

}
unset($value);

print_r($accounts);

但未设置不起作用。如果使用 $value = null;在循环中然后会设置好。

【问题讨论】:

  • 那是因为您取消设置 $accounts[1]['active'] 而不是 $accounts[1]
  • 我听不懂。为什么要取消设置 $accounts[1]['active'] ?

标签: php foreach unset


【解决方案1】:

解决方案

$accounts = [
        0 => [
            "active" => true    
        ],
        1 => [
            "active" => false    
        ]
];

foreach($accounts as $index=>$value) {

    if($value['active'] === false) {
        var_dump($value);
        unset($accounts[$index]);
    }

}
//unset($value);

print_r($accounts);

【讨论】:

  • 很好,但是为什么不直接用 & 修改可以解释一下?
  • 因为当您 unset($value); 时,您正在取消设置 $accounts[1]['active'] 而不是 $accounts[1]
  • 因为foreach返回数组的每一部分
猜你喜欢
  • 1970-01-01
  • 2013-05-16
  • 2011-04-21
  • 2019-05-11
  • 2023-03-06
  • 2013-11-01
  • 2016-05-23
  • 2018-08-22
相关资源
最近更新 更多