Return to Snippet

Revision: 64640
at September 2, 2013 08:56 by gummiost


Updated Code
function array_traverse($arr)
{
	static $recursive_array = array(); // Static to mantain state when doing recursive function

	// Traverse array, if a value is an array do recursive call to traverse that array 
	foreach($arr as $value)
	{
		if(is_array($value))
		{
			array_traverse($value);
		}
		else
		{
			$recursive_array[] = $value;
			echo $value."<br />\n";
		}
	}
	
	return $recursive_array;
}

$arr = array(1, array(141,151,161), 2, 3, 5, array(101, 202, array(303,404)));

var_dump(array_traverse($arr));

Revision: 64639
at September 2, 2013 08:53 by gummiost


Initial Code
function array_traverse($arr)
{
	static $recursive_array = array(); // Static to mantain state when doing recursive function

	// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
	foreach($arr as $value)
	{
		if(is_array($value))
		{
			array_traverse($value);
		}
		else
		{
			$recursive_array[] = $value;
			echo $value."<br />\n";
		}
	}
	
	return $recursive_array;
}

$arr = array(1, array(141,151,161), 2, 3, 5, array(101, 202, array(303,404)));

var_dump(array_traverse($arr));

Initial URL

                                

Initial Description
Traverses a multidimensional array and returns an array with the results. It also echoes the result as a string just for demonstration.

Initial Title
Recursive multidimensional array traversing

Initial Tags
php, array

Initial Language
PHP