How to get array_walk to work with PHP built-in functions?

I just want to use array_walk() with ceil() to round all elements of the array. But that will not work.

Code:

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

output should be: 3.6, -10

Error message:

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

: 3,5,5, -10,5 (Same as before using ceil ())

I also tried with round() .

+6
source share
4 answers

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

 function myCeil(&$list){ $list = ceil($list); } $numbs = array(3, 5.5, -10.5); array_walk($numbs, "myCeil"); print_r($numbs); 
+3
source

Use array_map .

 $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 do not like to call with too many parameters (there is a note about this on the documentation page for array_walk ). This is just a warning, but it is not a mistake.

array_walk also requires that the first callback parameter be a reference if you want it to modify the array. Thus, ceil() was still called for each element, but since it did not take the value as a reference, it did not update the array.

array_map better for this situation.

+7
source

This is because array_walk needs a function whose first parameter is the & link

 function myCeil(&$value){ $value = ceil($value); } $numbs = array(3, 5.5, -10.5); array_walk($numbs, "myCeil"); print_r($numbs); 
+2
source

The reason this does not work is because ceil($param) expects only one parameter instead of two.

What can you do:

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

If you want to keep these values, go array_map and use array_map , which returns an array.

UPDATE

I suggest reading this answer in stackoverflow, which explains very well the differences between array_map , array_walk and array_filter

Hope this helps.

+2
source

Source: https://habr.com/ru/post/981405/


All Articles