Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between count and sizeof?

Tags:

php

I would like to count the number of values i have in some array.

what is the difference between count and sizeof?

$recips = array();
echo count($recips);
echo sizeof($recips);
like image 901
Roi Avatar asked Mar 02 '15 11:03

Roi


2 Answers

'sizeof' is an alias of 'count' - at least according to the PHP manual!

In reality, the two functions behave differently, at least regarding the execution time - sizeof takes significantly longer to execute!

The conclusion is: sizeof is NOT an alias for count

Example:

<?php
$a = array();
for ($i = 0; $i < 1000000; ++$i) {
    $a[] = 100;
}


function measureCall(\Closure $cb)
{
    $time = microtime(true);
    call_user_func($cb);
    return microtime(true) - $time;
}

for ($i = 0; $i < 3; ++$i) {
    echo measureCall(function () use ($a) {
            for ($i = 0; $i < 10000000; ++$i) {
                count($a);
            }
        }) . " seconds for count!\n";

    echo measureCall(function () use ($a) {
            for ($i = 0; $i < 10000000; ++$i) {
                sizeof($a);
            }
        }) . " seconds for sizeof!\n";
}

The outcome is:

0.9708309173584 seconds for count!
3.1121120452881 seconds for sizeof!
1.0040831565857 seconds for count!
3.2126860618591 seconds for sizeof!
1.0032908916473 seconds for count!
3.2952871322632 seconds for sizeof!

Update: This test was executed on PHP 7.2.6

like image 109
Thomas Moser Avatar answered Nov 12 '22 20:11

Thomas Moser


These functions are aliases, like mentioned -> http://php.net/manual/en/function.sizeof.php

like image 41
Mihir Bhatt Avatar answered Nov 12 '22 22:11

Mihir Bhatt