Useful array functions

Here area couple of array functions which I keep on finding myself searching for.

objectToArray converts an object into an array. This is not as trivial as it sounds, but luckily a PHP function exists that sort of does this, json_decode. The object is first converted into JSON then decoded from JSON into an associative array:

function objectToArray( $object )
	{
		if( is_object( $object ) )
		{
			return json_decode( json_encode($object), true );
		}

		return $object;
	}

flattenArray converts a multi-dimensional array into a flat array containing only the values:

function flattenArray( $arr = [] )
{
	$return = array();
	array_walk_recursive($arr, function($a) use (&$return) { $return[] = $a; });
	return $return;
}

This came from StackOverflow: http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array

Leave a Reply

Your email address will not be published. Required fields are marked *