Asim Zaidi
Asim Zaidi

Reputation: 28284

size of an array

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

Upvotes: 1

Views: 586

Answers (3)

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

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

Upvotes: 4

Jacob
Jacob

Reputation: 8334

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

Upvotes: 2

nybbler
nybbler

Reputation: 4841

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.

Upvotes: 2

Related Questions