Recursively cast to array in PHP

·

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 casteverything to an array. For example, this is what happens when we cast 1to 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 );
}

Comments

4 responses to “Recursively cast to array in PHP”

  1. Juan Pablo Avatar
    Juan Pablo

    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.

Leave a Reply to Zain KhalidCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading