PHP try to emulate functional programming by providing the functions like array_reduce. But what they lack is the knowledge of principals of functional programming.
I had a problem where there are multiple arrays and need to be merged. array_merge function works only on 2 arrays. Merging multiple arrays need a for loop OR use array_reduce function [I thought]. But it turns out that array_reduce function is not functional as I imagined. Even though the documentation say that the last parameter to this function is the initial value for the array fold function, actually it is not.
If the initial parameter is not an integer, PHP will default to zero. For the above problem I tried the following
array_reduce($my_arrays, "array_merge", array());
What I expected it is to work as
$initial = array();
foreach ( $my_arrays as $m ) { $initial = array_merge($initial, $m); }
What I got was
PHP Warning: array_merge(): Argument #1 is not an array in Command line code on line 1
PHP Warning: array_merge(): Argument #1 is not an array in Command line code on line 1
These kind of behavior will lead to serious problem in the system and is hard to debug.
No comments:
Post a Comment