is there a way of finding the sizeof an array without using sizeof($array) and / or count($array)?
4
-
4what is the restriction that u can not use both function??xkeshav– xkeshav2011-03-11 06:42:32 +00:00Commented Mar 11, 2011 at 6:42
-
2Why do you want any other if there are already 2 functions.? Are you having any problem with this?Awais Qarni– Awais Qarni2011-03-11 06:44:07 +00:00Commented Mar 11, 2011 at 6:44
-
@diEcho. I second that questionBen– Ben2011-03-11 06:44:23 +00:00Commented Mar 11, 2011 at 6:44
-
Up-voted the answers to counter whoever decided to down-vote valid answers to a bad question.Jacob– Jacob2011-03-11 07:03:26 +00:00Commented Mar 11, 2011 at 7:03
Add a comment
|
3 Answers
If you want to know the number of items in an array, you have two solutions :
- Using the
count()function -- that's the best idea - Looping over all items, incrementing a counter -- that's a bad idea.
For an example using the second idea :
$num = 0;
foreach ($array as $item) {
$num++;
}
echo "Num of items : $num";
But, again : bad idea !
**Edit :** just for fun, here's another example of looping over the array, but, this time, using [**`array_map()`**][1] and an anonymous function *(requires PHP >= 5.3)* :
$array = array(1, 2, 3, 4, 5);
$count = 0;
array_map(function ($item) use (& $count) {
$count++;
}, $array);
echo "Num of items : $count";
Here, too, bad idea -- even if fun ^^
Comments
You could use foreach and manually count the number of elements in the array, but I don't see why you would want to since this will provide no advantage over using either the sizeof or count functions.
1 Comment
Asim Zaidi
there is no particular reason. I just wanted to do it manually at once. thanks
Even though there is no point doing a foreach or anything else for that matter... what about array_reduce:
array_reduce($array, function($count, $element) {
return $count + 1;
}, 0);
Just for something different :D
1 Comment
Mark Baker
+1 I always like the "just for something different" answers, especially when they're clever. PHP >= 5.3 of course