How to use the PHP Count Function

How to use the php count function

PHP's count function, another great pre-built function at your disposal, is a great way to count elements in arrays and objects that implement the countable interface. We will explore how this function works, along with code examples, tips, and of course, all backed by best practice guidelines. We'll also discuss the recent changes to this function that came with the version 8.0+ branch of PHP. Let's jump in and learn how to use the PHP count() function in your next web project.

The count function in PHP

The count function is a pre-built function in PHP, just like the sleep function, or the mkdir function, that you can use in your codebase to count the number of elements in a given value. The count function counts elements inside arrays and objects that are Countable. Passing anything other than these two types will throw a "TypeError" warning in PHP 8, a standard warning in PHP 7, and nothing in anything prior to PHP 7. The count function will then return an int value with the number of elements found. There is also another function called "sizeof", which is just an alias of count(). Therefore it behaves exactly the same, should you see it in other codebases.

PHP array length

The easiest way to find an array's length in PHP is to use the count function. We'll explore the answer to this question in this guide along with PHP code examples of how to find the length of an array with PHP.

How do you use the count function?

Let's explore how the count function works by looking at some PHP code examples. This is the basic example of the count function, where we have an array of 5 items, and therefore count displays 5.

$array = [1, 2, 3, 4, 5];

# Will output 5
var_dump(count($array));

Let's add some values to our keys, to check that count() still returns 5, like the following.

$array = [1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e'];

# Will output 5
var_dump(count($array));

Next, let's switch up the array and turn it into a multidimensional array. The count should still be 5. This is because the count can take up to two different parameters. The first is the array or countable object, the second is the count mode. By default, the count's count mode is "COUNT_NORMAL". This is called the mode and is an optional parameter. In the example below, we're not telling PHP to count inside the multidimensional array, instead, we're only counting the parent keys.

$array = [
 1 => [
 'a' => 'b'
 ], 
 2 => [
 'c' => 'd'
 ],
 3 => [
 'e' => 'f'
 ], 
];

# Will output 3, because of COUNT_NORMAL
var_dump(count($array));

Let's now tell PHP to count all the items in the array, recursively, because we want the full item count as it's a multidimensional array. To do this we use the flag "COUNT_RECURSIVE" (or you could just use "1"). Another great thing about PHP is, this function will also detect recursion to help avoid infinite loop issues. If one is detected, it will trigger an "E_WARNING".

$array = [
 1 => [
 'a' => 'b'
 ], 
 2 => [
 'c' => 'd'
 ],
 3 => [
 'e' => 'f'
 ], 
];

# Will output 6
var_dump(count($array, COUNT_RECURSIVE));

Let's see an example when passing a Countable object instead of an array. Here, we have a class that implements Countable, therefore must contain at least 1 abstract method and implement the (Countable::count). Therefore, we've added the public function count() to our class. Failure to do so will trigger a PHP fatal error.

class CountObject implements Countable
{
 protected $ourCount = 3;
 
 public function count(): int
 {
 return $this->ourCount;
 }
}

# Will output 3
var_dump(count(new CountObject()));

What changes have been made to the count function in PHP 7 and PHP 8?

Before PHP 7.2, passing a value to the count function that wasn't either an array or countable object, resulted in no error. However, since 7.2, this triggers a warning, and since PHP 8.0 this will trigger a "TypeError". With version PHP 8.0, this will help developers debug quicker and help avoid bugs where you expect one thing and get the other.

Conclusion

The count function in PHP is a great and fast way to check object and array sizes. Using the "sizeof" function will achieve the same number, as it's an alias, and since PHP 8.0, this function has become stricter.

  • In PHP 7.2, count() will throw a warning if invalid types (non-countable values) are passed to the function, and in PHP 8.0, this was changed to a "TypeError"
  • Prior to PHP 8.0, the count() function does return "1" even if the value passed to the function was a non-countable value
  • Prior to PHP 8.0, if null is passed to the count() function it will return "0"
  • The sizeof() function is an alias of the count and behaves the same way as the count()

Senior PHP developer with near two decades of PHP experience. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all