Jump to content

Creating 'count' function as training - problem with multidimensional arrays


tangar

Recommended Posts

hi ho!
I'm rookie and wanna create count function from zero as training (just to learn some stuff about arrays). What I got:
 

<?
	$menu = array (
		array('link'=>'Magic', 'href'=>'9.php'),
		array('link'=>'Poker', 'href'=>'10.php'),
		array('link'=>'Number', 'href'=>'11.php'),
		array('link'=>'Count', 'href'=>'12.php'),
		array('link'=>'Size', 'href'=>'13.php')
	);

function myCount ($count, $mode=0) { // mode - if it would be multidimensional array
	if (is_array($count)){
			$b=0; // if array would be empty
			foreach ($count as $a) {
					if (is_array($a) and $mode==1)
					$b += myCount($a, 1);		
				$b++;
			}
	} elseif (is_null($count)){
	$b = 0;
	} else {
	$b = 1;
	}
print "$b";
}

myCount ($menu, 1);

?>

It counts normal arrays ok, but it counts too much with multidimensional. To count them I'm making recursion, but it seems it doesn't work corrent; aswer is '222225' lol :D

 

Please help! :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.