ILMV Posted February 14, 2009 Share Posted February 14, 2009 Hello all If I count() this array... array('1','2','3','4'); it returns 4, but I want to count this array... array(array('1','2'),array('3','4')); and I want it to return 4, the total number of values within all nested array. Is there a way to do this without having to use a foreach loop? Many Thanks Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/ Share on other sites More sharing options...
ILMV Posted February 14, 2009 Author Share Posted February 14, 2009 Also to add.. I have tried to use count($arr,COUNT_RECURSIVE); but it would add my original array up to 6, not 4, as it adds the nested arrays as a single value, and then continues to count the array values. Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/#findComment-762421 Share on other sites More sharing options...
ILMV Posted February 14, 2009 Author Share Posted February 14, 2009 Resolved, I found this function rcount ($array) { $count = 0; if (is_array($array)) { foreach($array as $id=>$sub) { if (!is_array($sub)) { $count++; } else { $count = ($count + $this->rcount($sub)); } } return $count; } return FALSE; } Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/#findComment-762423 Share on other sites More sharing options...
allworknoplay Posted February 15, 2009 Share Posted February 15, 2009 I don't understand, you said you wanted to do this without a foreach loop and in your last post, there's a foreach loop!!! Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/#findComment-762453 Share on other sites More sharing options...
ILMV Posted February 18, 2009 Author Share Posted February 18, 2009 I know, what I should have said is 'if possible, without a foreach loop'. Upon research it would appear this if one of the only ways to count the array I have. Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/#findComment-765182 Share on other sites More sharing options...
premiso Posted February 18, 2009 Share Posted February 18, 2009 I know, what I should have said is 'if possible, without a foreach loop'. Upon research it would appear this if one of the only ways to count the array I have. You could use a for/while loop instead you know, just extra work. But as for being more efficient, doubtful. Link to comment https://forums.phpfreaks.com/topic/145240-counting-an-array/#findComment-765237 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.