DEV Community

Youn
Youn

Posted on

PHP count() Function – Check Array Length

😄 This post is based on the content from coding.courses.

(PHP Version | 4+)

Definition and Usage

The count() function counts the number of elements (array length) in an array and returns an integer.

This function also counts the number of elements in objects that implement the Countable interface and returns an integer.

Basic Example

/* Numerically indexed array */
$array_1 = [1, 2, 3, 4, 5];
var_dump(count($array_1)); // int(5)

$array_2 = [];
var_dump(count($array_2)); // int(0)

$array_2[0] = 1;
$array_2[1] = 2;
var_dump(count($array_2)); // int(2)

/* Associative array */
$associative_array = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
];
var_dump(count($associative_array)); // int(3)

/* Multidimensional array */
$multi_dimensional_array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
var_dump(count($multi_dimensional_array)); // int(3)

// Returns the total number of elements, including all nested array elements
var_dump(count($multi_dimensional_array, 1)); // int(12)
Enter fullscreen mode Exit fullscreen mode

Syntax

count(Countable|array $value, int $mode = COUNT_NORMAL): int
Enter fullscreen mode Exit fullscreen mode

Parameters

$value

The array, or the object implementing the Countable interface, whose elements are to be counted.

$mode

Optional.
This parameter can accept one of the following constants: COUNT_NORMAL (or 0) or COUNT_RECURSIVE (or 1). The default is COUNT_NORMAL.

  • COUNT_NORMAL (or 0): Returns the number of elements in the array. This is the default mode.
  • COUNT_RECURSIVE (or 1): Recursively counts all elements in a multidimensional array. It returns the total count, including all elements inside nested arrays.

Return Values

Returns the number of elements as an integer.

  • If the parameter was null, the function returned 0.
  • If the parameter was a non-null value, the function returned 1.

Starting with PHP 8.0.0,
if the parameter is neither an array nor an object implementing the Countable interface, a TypeError exception is thrown. This is a change from the previous behavior where the function always returned 1 for non-null values. This change has made the behavior of the function clearer and more explicit, and reduced confusion that could occur in earlier versions.

# Setting the Element Counting Mode for Multidimensional Arrays

A multidimensional array that includes sub-arrays is an array where elements are arrays that can themselves contain other elements. To include all elements inside nested arrays when counting, set the second parameter of the count() function to COUNT_RECURSIVE or 1.

With this setting, the count() function recursively counts all elements in the multidimensional array and returns the total number of elements, including those inside nested arrays.

$multi_dimensional_array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
var_dump(count($multi_dimensional_array)); // int(3)

// Returns the total number of elements, including all nested array elements
var_dump(count($multi_dimensional_array, 1)); // int(12)
Enter fullscreen mode Exit fullscreen mode

Counting the Number of Elements in Objects That Implement the Countable Interface

The count() function counts the number of elements in objects that implement the Countable interface, as well as in arrays, and returns the result as an integer.

As a simple example, let's create a class that implements the Countable interface. This class includes a method that returns the length of a string, and by implementing the Countable interface, it allows the number of elements for that class to be counted.

class String_Length_Counter implements Countable {
    private $string;

    public function __construct($string) {
        $this->string = $string;
    }

    public function get_string_length(): int {
        return strlen($this->string);
    }

    // Implement Countable interface method (PHP 8.1+ compatible)
    public function count(): int {
        return $this->get_string_length();
    }
}

// Create String_Length_Counter object
$counter = new String_Length_Counter("Hello, world!");

// Use count() function to count elements in the object
echo "String length: " . count($counter); // Output: 13
Enter fullscreen mode Exit fullscreen mode

In this example, the String_Length_Counter class implements the Countable interface and defines the count() method.
This method calls the get_string_length() method, which returns the length of the string, and returns that value. The count() function is then used to calculate the length of the String_Length_Counter object.

References

PHP count() Function – Check Array Length - codingCourses

The count() function function counts the number of elements (array length) in an array and returns an integer. This function also counts the number of elements in objects that implement the Countable interface and returns an integer.

favicon coding.courses

Top comments (0)