List array Recursively in PHP

Code :

function listArrayRecursive($array_name, $ident = 0){
	if (is_array($array_name)){
		foreach ($array_name as $k => $v){
			if (is_array($v)){
				for ($i=0; $i < $ident * 10; $i++){ echo " "; }
				echo $k . " : " . "
"; listArrayRecursive($v, $ident + 1); }else{ for ($i=0; $i < $ident * 10; $i++){ echo " "; } echo $k . " : " . $v . "
"; } } }else{ echo "Variable = " . $array_name; } }

Usage :

$ages = array(
				"ahmed" => "25",
				"mohamed" => "35",
				"group" => array("omar" => "15", "abdalla" => "20", "sub group" => array("john" => "10", "peter" => "20")));
 
listArrayRecursive($ages);

Output will be printed array in indented way.

5
Leave a Reply

avatar
4 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Ahmed AbdelaliemMe2reshNiko Kivelä Recent comment authors
  Subscribe  
Notify of
Niko Kivelä
Guest
Niko Kivelä

Hello, great article for newcomers. Tho your function ain’t working. It misses $i from $i $v) { print str_repeat(‘ ‘, $ident * 10) . $k . ‘ : ‘; if (is_array($v)) { print “\n”; listArrayRecursive($v, $ident + 1); return; } print $v . “\n”; } }

sotiris
Guest
sotiris

thanks man

Ahmed Samir
Guest
Ahmed Samir

Am I wrong or you just need to use:

echo '<pre>'; print_r($data); echo '</pre>';

instead?