Hướng dẫn
Quảng cáo

Hàm count() trong PHP

Hướng dẫn cách sử dụng hàm count() về mảng trong lập trình PHP

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+


The basic syntax of the count() function is given with:

count(array, mode);

The following example shows the count() function in action.

// Sample array
$cars = array("Audi", "BMW", "Volvo", "Toyota");
// Display array elements count
echo count($cars);


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:

// 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:

class MyClass implements Countable
    protected $number = 4;

    public function count(){
        return $this->number;


// Creating object
$countable = new MyClass();
echo count($countable); // Prints: 4

Bài viết này đã giúp ích cho bạn?

Bài viết mới