I recently ran into an issue where JSON encoding some objects in my code wasn’t working properly. After experimenting, I realized that casting everything to an array before JSON encoding magically fixed things.
Casting an object to an array is simple enough:
$variable_to_array = (array) $object_var;
But, what happens when an object or array contains references to other objects or arrays? The answer is that we then need to recursively cast a given input to an array. But, we don’t necessarily want to recursively cast everything to an array. For example, this is what happens when we cast 1
to an array:
return (array) 1;
=> array(1) {
[0]=>
int(1)
}
A simple fix is to recursively cast non-scalar values to an array. Here’s an example of how we would do that:
/**
* Given mixed input, will recursively cast to an array if the input is an array or object.
*
* @param mixed $input Any input to possibly cast to array.
* @return mixed
*/
function recursive_cast_to_array( $input ) {
if ( is_scalar( $input ) ) {
return $input;
}
return array_map( 'recursive_cast_to_array', (array) $input );
}
4 responses to “Recursively cast to array in PHP”
Simple but very useful. Thank you for the tip.
You’re welcome! Thanks for leaving a comment.
I gave it a try, it is really great. Concise code has a beauty of its own. Thanks for sharing Eric. Loved it.
Thanks for the code Eric!
I believe this could be improved by updating the return statement like the following:
return array_map( __FUNCTION__, (array) $input );
Just to play nicely with namespaces.