tangar Posted September 11, 2017 Share Posted September 11, 2017 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 Please help! Link to comment Share on other sites More sharing options...
requinix Posted September 12, 2017 Share Posted September 12, 2017 count() is not recursive. Just don't do anything multi-dimensional. [edit] WTF am I saying? Ignore that. Link to comment Share on other sites More sharing options...
cyberRobot Posted September 12, 2017 Share Posted September 12, 2017 To count them I'm making recursion, but it seems it doesn't work corrent; aswer is '222225' lol 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 Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.