Search code examples
phparrays

Deleting rows in callback function in array_walk()


I'm trying to work with array using array_walk() function such way:

<?php

$array = array('n1' => 'b1', 'n2' => 'b2', 'n3' => 'b3');

array_walk($array, function(&$val, $key) use (&$array){
    echo $key."\n";
    if ($key == 'n1')
        $val = 'changed_b1';
    if ($key == 'n2' || $key == 'n3') {
        unset($array[$key]);
    }
});

print_r($array);

Get:

n1
n2
Array
(
    [n1] => changed_b1
    [n3] => b3
)

It seems, what after deletion of 2nd element -- 3rd element don't be sended to callback function.


Solution

  • What you can do is use a secondary array, which will give the effect that those nodes have been deleted, like;

    $array = array('n1' => 'b1', 'n2' => 'b2', 'n3' => 'b3');
    
    $arrFinal = array();
    array_walk($array, function($val, $key) use (&$array, &$arrFinal){
        echo $key."\n";
        if ($key == 'n2' || $key == 'n3') {
            //Don't do anything
        } else {
           $arrFinal[$key] = $val;
        }
    });
    
    print_r($arrFinal);