Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting rows in callback function in array_walk()

Tags:

arrays

php

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.

like image 605
mochalygin Avatar asked Oct 15 '14 08:10

mochalygin


People also ask

What is the difference between array_walk and array_map?

The array_walk() function is not affected by the internal array pointer of the array. It will traverse through all the elements. The array_map() cannot operate with the array keys, while the array_walk() function can work with the key values pair.

What is array_ walk in PHP?

The array_walk() function is an inbuilt function in PHP. The array_walk() function walks through the entire array regardless of pointer position and applies a callback function or user-defined function to every element of the array. The array element's keys and values are parameters in the callback function.

How to use array_ filter in PHP?

The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

What is array_map function in PHP?

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. Tip: You can assign one array to the function, or as many as you like.


2 Answers

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

like image 170
m6w6 Avatar answered Oct 31 '22 11:10

m6w6


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

<?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

like image 21
ʰᵈˑ Avatar answered Oct 31 '22 11:10

ʰᵈˑ