Deleting lines in callback function in array_walk ()

I am trying to work with an array using the array_walk () function this 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 that after removing the second element - the 3rd element is not sent to the callback function.

+3


source to share


3 answers


What you can do is use a secondary array that allows you to remove these nodes, for example:

<?php

$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);

      



https://eval.in/206159

+3


source


Use array_filter:

<?php
$filtered = array_filter($array, function($v,$k) {
    return $k !== "n2" && $k !== "n3";
}, ARRAY_FILTER_USE_BOTH);
?>

      



See http://php.net/array_filter

+5


source


From the documentation :

Only array values ​​can be changed; its structure cannot be changed , i.e. the programmer cannot add, unset or change the order of elements. If the callback does not meet this requirement, the behavior of this function is undefined and unpredictable .

Maybe the reason why you are not getting the desired result with your code. Hope it helps.

Possible alternatives:

  • If you still want to use array_walk()

    , just create a new array and copy the "required" elements, i.e. the indices you don't want to delete into the new array. This is the preferred alternative if the number of items to be removed is very high.
  • You can look at array_filter or array_map , both rely on the application callback

    for each element of your array. You can simply put a condition against the indexes you want to delete in this callback function. This will work if the number of items you want to remove is very small.
  • If, however, the elements to be removed are contiguous and form a "part" of the array (in your case, you want to remove n2 and n3 that are adjacent). You can use array_splice function

Sidenote - I refrain from typing in any code snippets as I linked the relevant documents and start with should be a good exercise in itself.

0


source







All Articles