I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.
I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)
I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.
I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)
According to phpbench:
Is it worth the effort to calculate the length of the loop in advance?
//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);
for ($i=0; $i<$size; $i++) {
//...
}
//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
//...
}
A loop with 1000 keys with 1 byte values are given.
| count() | sizeof() | |
|---|---|---|
| With precalc | 152 | 212 |
| Without precalc | 70401 | 50644 |
(time in µs)
So I personally prefer to use count() instead of sizeof() with pre calc.
'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 < 1000000; ++$i) {
$a[] = 100;
}
function measureCall(\Closure $cb)
{
$time = microtime(true);
call_user_func($cb);
return microtime(true) - $time;
}
for (
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
These functions are aliases, like mentioned -> http://php.net/manual/en/function.sizeof.php