9

I just want to use array_walk() with ceil() to round all the elements within an array. But it doesn't work.

The code:

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

output should be: 3,6,-10

The error message:

Warning: ceil() expects exactly 1 parameter, 2 given on line 2

output is: 3,5.5,-10.5 (Same as before using ceil())

I also tried with round().

0

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome :-) Sometimes one array_* function is better than another, depending on the situation.
2

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
)

Comments

2

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.

1 Comment

Not quite. The warning says "ceil() expects exactly 1 parameter, 2 given". array_walk will call your callback function and pass it 2 parameters ($value and $key). The array wasn't getting updated because array_walk will only do that if the $value parameter is a reference (and its value is updated in the callback).
2

That is because array_walk needs function which first parameter is a reference &

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

$numbs = array(3, 5.5, -10.5); 
array_walk($numbs, "myCeil"); 
print_r($numbs); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.