1

is there a way of finding the sizeof an array without using sizeof($array) and / or count($array)?

4
  • 4
    what is the restriction that u can not use both function?? Commented Mar 11, 2011 at 6:42
  • 2
    Why do you want any other if there are already 2 functions.? Are you having any problem with this? Commented Mar 11, 2011 at 6:44
  • @diEcho. I second that question Commented Mar 11, 2011 at 6:44
  • Up-voted the answers to counter whoever decided to down-vote valid answers to a bad question. Commented Mar 11, 2011 at 7:03

3 Answers 3

4

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 ^^

Sign up to request clarification or add additional context in comments.

Comments

2

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

there is no particular reason. I just wanted to do it manually at once. thanks
2

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

+1 I always like the "just for something different" answers, especially when they're clever. PHP >= 5.3 of course

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.