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.
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With