PHP array: count or sizeof?


Para encontrar el número de elementos en un PHP $array, que es más rápido/mejor/más fuerte?

count($array) o sizeof($array) ?

Editar

Gracias a Andy Lester, he refinado mi pregunta para que signifique desde una perspectiva multilingüe. Los comentaristas del manual dicen

"[sizeof] no significa lo mismo en muchos otros lenguajes basados en C"

¿Es esto cierto?

 171
php
Author: I am the Most Stupid Person, 2010-10-20

7 answers

Usaría count() si son iguales, ya que en mi experiencia es más común, y por lo tanto hará que menos desarrolladores que lean tu código digan "sizeof(), ¿qué es eso?"y tener que consultar la documentación.

Creo que significa que sizeof() no funciona como lo hace en C (calculando el tamaño de un tipo de datos). Probablemente hizo esta mención explícitamente porque PHP está escrito en C, y proporciona una gran cantidad de envoltorios con nombres idénticos para las funciones de C(strlen(), printf(), etc)

 153
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-24 02:11:07

De acuerdo con phpbench :

¿Vale la pena el esfuerzo de calcular la longitud del bucle de antemano?

//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);
    //...
}

Se da un bucle con 1000 teclas con valores de 1 byte.

Con pre - calc-count () Tiempo total: 152 µs

Sin pre - calc-count () Tiempo total: 70401 µs

Con pre calc-sizeof () Tiempo total: 212 µs

Sin pre - calc-sizeof () Tiempo total: 50644 µs

Así que personalmente prefiero use count () en lugar de sizeof() con pre calc .

 76
Author: Reza Baradaran Gazorisangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 18:21:38

Son idénticos según sizeof()

En ausencia de cualquier razón para preocuparse por "más rápido", siempre optimizar para el ser humano. ¿Qué tiene más sentido para el lector humano?

 33
Author: Andy Lester,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-08 01:26:23

Según el sitio web, sizeof() es un alias de count(), por lo que deberían estar ejecutando el mismo código. Tal vez sizeof() tiene un poco de sobrecarga porque necesita resolverlo a count()? Sin embargo, debería ser muy mínimo.

 16
Author: Andy Groff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-29 13:23:45

sizeof() es solo un alias de count() como se menciona aquí

Http://php.net/manual/en/function.sizeof.php

 2
Author: Mina Ragaie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 07:35:32

Sé que esto es viejo, pero solo quería mencionar que Probé esto :

<?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() took ".(time()-$time)." sec\n");

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

Y el resultado fue:

1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec

Así que solo usa count().

 1
Author: Mehdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 02:36:14

Utilice la función count, Aquí hay un ejemplo de cómo contar matriz en un elemento

$cars = array("Volvo","BMW","Toyota");
echo count($cars);

La función count() devuelve el número de elementos de un array.

La función sizeof() devuelve el número de elementos de un array.

La función sizeof() es un alias de la función count().

 -1
Author: Harish rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-07 12:56:05