0

Server nginx+php-fpm php 7.2

I tried 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);

But unset not working. If use $value = null; in cycle then will set fine.

2
  • Thas because you are unsetting $accounts[1]['active'] and not $accounts[1] Commented Jul 18, 2019 at 11:11
  • I can't understand. Why unsetting $accounts[1]['active'] ? Commented Jul 18, 2019 at 11:31

1 Answer 1

1

Solution

$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);
Sign up to request clarification or add additional context in comments.

4 Comments

Fine, but why not working directly modify with & Can explain?
Because when you unset($value); you are unsetting $accounts[1]['active'] and not $accounts[1]
because foreach return each part of array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.