How to Use PHP count() to Get Array Length

php count function

PHP developers may be need to determine the number of elements in an array. The count() function in PHP makes this simple and quick. If you build a website or an application, you’ll need to use count(). In this article, you will learn how the PHP count function works, what it does and how to use it.

Understand the count Function in PHP

The count() function returns the number of elements in an array or a Countable object. You can use it on both indexed and associative arrays. It helps you control loops such as manage data checks and get total values.

Arrays store a group of values. Sometimes, you need to check how many items the array contains. That’s where count() helps. It tells you how many entries you have in that array, whether it’s 3, 10, or zero.

Here is the syntax:

count(array, mode);
  • The first argument is your array or countable object.
  • The second argument is optional. It defines how deep the count should go.

For example:

$items = [1, 2, 3];
echo count($items); // Outputs: 3

The count() returns 3 because the array contains three elements.

The second parameter, $mode, changes how count() reads a nested array.

  • COUNT_NORMAL is the default setting. It counts only the top-level elements.
  • COUNT_RECURSIVE counts elements inside nested arrays as well.

Look at the difference:

$data = [1, 2, [3, 4]];
echo count($data); // Outputs: 3
echo count($data, COUNT_RECURSIVE); // Outputs: 5

PHP counts only [1, 2, [3, 4]] as three elements without recursion. But with COUNT_RECURSIVE mode, it dives into [3, 4] and counts them too.

Use COUNT_RECURSIVE if you want a full count of everything inside the array, even inner arrays.

But, there are cases where count() is not the right tool. If your data is not an array or object that implements countable, count() returns fatal error or 0.

For example:

$var = null;
echo count($var);

Here is the output in PHP 8.0 (modern version):

Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given in /index.php:2

Output in PHP 7.2:

Warning: count(): Parameter must be an array or an object that implements Countable in /index.php:2
0

Output of PHP 7.0:

0

You can use another built-in PHP function to check if the value is countable. For example:

$var = null;
echo is_countable($var) ? count($var) : 0;

If the value of $var is countable, it assigns its count; otherwise, it assigns zero.

How count() Works in PHP

Indexed arrays:

$colors = ['Red', 'Green', 'Blue'];
$total = count($colors);
echo $total; // Outputs: 3

Here the count() gives 3 because the array holds three values. This helps you to loop through the array or just display how many options a user has.

You can run conditional checks too:

if (count($colors) > 0) {
    echo "There are colors in the array.";
}

Associative arrays:

$user = ['name' => 'Alice', 'age' => 25, 'city' => 'New York'];
echo count($user); // Outputs: 3

The function counts all key-value pairs. It does not care about the key names. As long as the item exists, it adds to the total.

You can use this to check user data:

if (count($user) < 1) {
    echo "User data is empty";
}

Multidimensional arrays:

$matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
];

The count($matrix) returns 3, because it sees three top-level arrays.

To count everything:

echo count($matrix, COUNT_RECURSIVE); // Outputs: 9

PHP counts the main arrays and the inner values as well. Make sure to check the data’s depth before deciding how to count it.

The Difference Between count() and sizeof() in PHP

Both count() and sizeof() return the number of elements in an array. They work the same because sizeof() is just an alias for count().

For example:

$items = ['pen', 'book'];
echo count($items);  // 2
echo sizeof($items); // 2

Both lines return 2. There is no performance difference between them. Internally, PHP handles them the same way.

Here is a table shows you the key differences:

Featurecount()sizeof()
Main functionYesNo (alias)
Supports modeYesYes
Common usageMore commonLess common

So, are count() and sizeof() the same?

Yes, they work the same. The only difference is the name. count() is more common and easier for others to understand when reading your code.

PHP’s count() and Custom Classes

The count() does not work well with general objects by default.

class MyBox {}
$obj = new MyBox();
echo count($obj); // Warning in PHP 7.2+

You must implement the Countable interface if you want count() to work on an object.

Here are the outputs for various PHP versions:

// => PHP 8.1
Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, MyBox given in /index.php:3

// => PHP 7.2
Warning: count(): Parameter must be an array or an object that implements Countable in /index.php on line 3
1

// => Before PHP 7.2
1

The Countable interface lets you define how the count should happen.

You must create a method named count() in your class. PHP will call this method when you use count().

Here is an example:

<?php 

class ProductList implements Countable {
    private $products = [];

    public function add($item) {
        $this->products[] = $item;
    }

    public function count(): int {
        return count($this->products);
    }
}

$list = new ProductList();
$list->add('Phone');
$list->add('Laptop');

echo count($list); // Outputs: 2

You give PHP a clear way to count your object’s contents when use the Countable interface. This works well for custom data collections and inventory lists.

Wrapping Up

In this article, you learned how the PHP count function works and where it fits in your code. You also saw how to use it with arrays, multidimensional structures, and even user-defined classes.

Here is a quick recap:

  • Use count() to know how many elements exist in an array or a Countable object.
  • Use the optional mode if you need to count inner children inside sub-arrays.
  • Store count results in a variable before loops to save performance time.
  • Always use COUNT_RECURSIVE carefully. It can sometimes return more than expected.
  • count() and sizeof() are the same, but count() is clearer.
  • To count objects, use the Countable interface.

FAQs

What is count() in PHP?

count() is a built-in PHP function. It tells you how many elements are in an array or countable object.

How to count total in PHP?

Use the count function like this:
$items = [1, 2, 3];
$total = count($items);
echo $total; // 3
This prints the total number of elements.

How to display count value in PHP?

Store the count in a variable and echo it.
$fruits = ['apple', 'banana'];
$total = count($fruits);
echo "Total fruits: " . $total; // Total fruits: 2
This shows the count to users. Adjust the message based on your needs.
Previous Article

How to Use the Ternary Operator in JavaScript

Next Article

Data Types in JavaScript: Primitive and Non-Primitive

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.