Array helpers trait

I’ve collected a number of utility functions for working with arrays over the years, mixed in with collections of ‘helper’ functions used in various projects and added to various classes.

They include testing for multi-dimensional arrays, obtaining a hash of an array and flattening arrays so they only contain values.

The way they were getting repeated in classes made me think they should be a trait: https://bitbucket.org/dgifford/array-helpers-trait

Determining if an array is multidimensional

This is quick boolean test to see if an array is multi-dimensional (contains other arrays). It simply checks each element in an array to see if it is also an array and returns true as soon as one is found:

function isArrayMultiDimensional( $arr = [] )
{
	if( is_array($arr) )
	{
		foreach( $arr as $key => $value )
		{
			if( is_array($value) )
			{
				return true;
			}
		}
	}
	return false;
}

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