sizeof

(PHP 4, PHP 5, PHP 7)

sizeofAlias de count()

Description

Cette fonction est un alias de : count().

add a note add a note

User Contributed Notes 5 notes

up
104
PixEye
10 years ago
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
up
56
chris at amis dot nl
5 years ago
I would recommend not using sizeof(). Many programmers expect sizeof() to return the amount of memory allocated. Instead sizeof() -as described above- is an alias for count().

Prevent misinterpretation and use count() instead.
up
27
umopdn [at] msn [dawt] com
10 years ago
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
up
1
septerrianin at mail dot ru
2 months ago
It's so fun to read people who believe that sizeof() is alias count().
Like  PixEye or umopdn.

NOTE:
Don't use sizeof()!
It's not alias of count()!
sizeof() is slower that count()!

Check it:
<?php
//Creating array with 1 000 000 elements
$a = array();
for (
$i = 0; $i < 1000000; ++$i)
{
   
$a[] = 100;
}

//Measure
$time = time();
for (
$i = 0; $i < 1000000000; ++$i)
{
   
$b = count($a);
}
print(
"1 000 000 000 iteration of count() taked ".(time()-$time)." sec\n");

$time = time();
for (
$i = 0; $i < 1000000000; ++$i)
{
   
$b = sizeof($a);
}
print(
"1 000 000 000 iteration of sizeof() taked ".(time()-$time)." sec\n");
?>

Shown:
1 000 000 000 iteration of count() taked 20 sec
1 000 000 000 iteration of sizeof() taked 31 sec

Any questions?
up
14
communiti.ch
10 years ago
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}
To Top