How to get array_walk working with PHP built in functions?

Use array_map instead.

$numbs = array(3, 5.5, -10.5);
$numbs = array_map("ceil", $numbs);
print_r($numbs);

array_walk actually passes 2 parameters to the callback, and some built-in functions don't like being called with too many parameters (there's a note about this on the docs page for array_walk). This is just a Warning though, it's not an error.

array_walk also requires that the first parameter of the callback be a reference if you want it to modify the array. So, ceil() was still being called for each element, but since it didn't take the value as a reference, it didn't update the array.

array_map is better for this situation.


I had the same problem with another PHP function. You can create "your own ceil function". In that case it is very easy to solve:

function myCeil(&$list){  
    $list =  ceil($list);  
}  

$numbs = [3, 5.5, -10.5];  
array_walk($numbs, "myCeil"); 

// $numbs output
Array
(
    [0] => 3
    [1] => 6
    [2] => -10
)

The reason it doesn't work is because ceil($param) expects only one parameter instead of two.

What you can do:

$numbs = array(3, 5.5, -10.5); 
array_walk($numbs, function($item) {
    echo ceil($item);
}); 

If you want to save these values then go ahead and use array_map which returns an array.

UPDATE

I suggest to read this answer on stackoverflow which explains very well the differences between array_map, array_walk, and array_filter

Hope this helps.

Tags:

Php

Arrays

Ceil