For a while, I used a "traditional" recursive function to smooth multidimensional arrays, such as
$baseArray = array(array('alpha'), array('beta','gamma'), array(), array(array('delta','epsilon'), array('zeta',array('eta', 'theta' ), ), ), array('iota'), );
to a simple 1-dimensional array.
Last night, I thought I'd see how to use array_walk_recursive () to find out if I could make it more efficient and clean.
My first attempt was not very successful:
function flattenArray($arrayValue, $arrayKey, &$flatArray) { $flatArray[] = $arrayValue; } $flattenedArray = array(); array_walk_recursive($baseArray,'flattenArray',$flattenedArray);
I thought this would work, but all I had was a series of errors:
Warning: Cannot use a scalar value as an array in C:\xampp\htdocs\arrayTest.php on line 16
and the result:
array(0) { }
The hint type in my flattenArray () function gave me
Catchable fatal error: Argument 3 passed to flattenArray() must be an array, integer given in C:\xampp\htdocs\arrayTest.php on line 16
Using closures gave identical results.
The only way I could get it to work (without using global or static for my flattenedArray) used a call time callback:
function flattenArray($arrayValue, $arrayKey, $flatArray) { $flatArray[] = $arrayValue; } $flattenedArray = array(); array_walk_recursive($baseArray,'flattenArray',&$flattenedArray);
which gives the correct result
array(9) { [0]=> string(5) "alpha" [1]=> string(4) "beta" [2]=> string(5) "gamma" [3]=> string(5) "delta" [4]=> string(7) "epsilon" [5]=> string(4) "zeta" [6]=> string(3) "eta" [7]=> string(5) "theta" [8]=> string(4) "iota" }
but gives me an unexpected warning
Deprecated: Call-time pass-by-reference has been deprecated in C:\xampp\htdocs\arrayTest.php on line 22
I know that PHP is a fancy language, but it seems a bit extreme. The documentation clearly shows that the first parameter to array_walk_recursive is pass by reference, but it seems that additional arguments can only be pass by reference during a call. Weird!
PHP Version - 5.3.8
Any suggestions on how I can use array_walk_recursive to smooth my array correctly, without getting obsolete errors (besides reporting an error).
EDIT
PS
I know that I can get around this problem using closure:
$flattenedArray = array(); array_walk_recursive($baseArray, function($arrayValue, $arrayKey) use(&$flattenedArray){ $flattenedArray[] = $arrayValue; } ); var_dump($flattenedArray);
but since this is required for a library that currently allows it to be used with PHP 5.2.0, this is not a practical use case for a function that requires a much later version of PHP