Tác dụng của hàm count()
The count()
function count all elements in an array, or something in an object.
The following table summarizes the technical details of this function.
Return Value: | Returns the number of elements in an array. |
---|---|
Changelog: | Since PHP 7.2.0 this function yield a warning on invalid countable types. |
Version: | PHP 4+ |
Syntax
The basic syntax of the count()
function is given with:
The following example shows the count()
function in action.
Example
Run this code »<?php
// Sample array
$cars = array("Audi", "BMW", "Volvo", "Toyota");
// Display array elements count
echo count($cars);
?>
Parameters
The count()
function accepts two parameters.
Parameter | Description |
---|---|
array | Required. Specifies an array or countable object. |
mode | Optional. If it is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. |
Note: The count()
function may return 0
for a variable that isn't set, or has been initialized with an empty array. Use isset()
function to test if a variable is set.
More Examples
Here're some more examples showing how count()
function basically works:
The following example demonstrates how to count all the elements in a multidimensional array recursively using the count()
function. Let's try it out and see how it works:
Example
Run this code »<?php
// Sample array
$cars = array(
"Audi" => array("RS7", "A8"),
"BMW" => array("Z4", "X7", "M8"),
"Mercedes" => array("GLA", "GLS"),
"Volvo" => array("XC90")
);
// Getting normal count
echo sizeof($cars); // Prints: 4
// Getting recursive count
echo sizeof($cars, 1); // Prints: 12
?>
If you want to use count($object)
and get the expected results your class has to implement the Countable interface, as demonstrates in the following example:
Example
Run this code »<?php
class MyClass implements Countable
{
protected $number = 4;
public function count(){
return $this->number;
}
}
// Creating object
$countable = new MyClass();
echo count($countable); // Prints: 4
?>