Jump to content

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


tangar
Go to solution Solved by cyberRobot,

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! :)

Edited by tangar
Link to comment
Share on other sites

  • Solution

To count them I'm making recursion, but it seems it doesn't work corrent; aswer is '222225' lol :D

 

You get that value because $b gets printed at the end of every function call. If you're looking for a running total, you would need to return $b.

http://php.net/manual/en/functions.returning-values.php

Edited by cyberRobot
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.