PHP count function
We can use the PHP count function on an array to count all its elements. It can also be used on an object, but the object must implement the Countable
interface. For example:
class MyClass implements Countable{ ... }
In addition to that, we should create a function count(): int
. This function will apply count
to a property or attribute that is an array. However, this goes beyond the topic we want to cover in this post. Nevertheless, I’ll provide an example at the end.
count(Countable|array $value, int $mode = COUNT_NORMAL): intSintaxis / Sintax
count($value); count($value,$mode);
Parameters
$value
– An array or an object that implements Countable
.
$mode
– This optional parameter is used for counting recursively, which is useful for counting elements in multidimensional arrays. However, when counting recursively, it also counts the elements within other arrays that are elements themselves.
To use this mode, you can use the following two values:
- 1
COUNT_RECURSIVE
Return
It returns the number of elements in the array.
PHP count examples
A simple example
Ejemplo simple de count$miarray = ["Pepe","Mario","Rodolfo","Cristian"]; echo count($miarray);
Example with object
el retorno de el metodo count debe ser especificacode desde PHP8class MiClase implements Countable { private $datos = array(); // Los datos que deseas contar public function agregarDato($dato) { $this->datos[] = $dato; } public function count(): int { return count($this->datos); } } // Crear un objeto de MiClase $objeto = new MiClase(); // Agregar datos al objeto $objeto->agregarDato('Dato 1'); $objeto->agregarDato('Dato 2'); $objeto->agregarDato('Dato 3'); // Contar los elementos del objeto utilizando count() $contador = count($objeto); echo "Número de elementos en el objeto: " . $contador;
Número de elementos en el objeto: 3