Table of Content
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: 3The count() returns 3 because the array contains three elements.
The second parameter, $mode, changes how count() reads a nested array.
COUNT_NORMALis the default setting. It counts only the top-level elements.COUNT_RECURSIVEcounts 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: 5PHP 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: 3Here 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: 3The 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: 9PHP 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); // 2Both 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:
| Feature | count() | sizeof() |
|---|---|---|
| Main function | Yes | No (alias) |
| Supports mode | Yes | Yes |
| Common usage | More common | Less 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: 2You 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_RECURSIVEcarefully. It can sometimes return more than expected. - count() and sizeof() are the same, but
count()is clearer. - To count objects, use the
Countableinterface.
FAQs
What is count() in PHP?
How to count total in PHP?
$items = [1, 2, 3];
$total = count($items);
echo $total; // 3
This prints the total number of elements.
How to display count value in PHP?
$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.
Similar Reads
The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…
The NOT operator in PHP (!) provides the reverse of whatever truth value is given by a certain expression. It’s…
PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times…
PHP array_flip swaps keys with values. It works well when you need values as keys in fast lookups. What is…
PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…
In regard to the use of constants in PHP, clear understanding of their definition and use could be critical in…
Use strtoupper() function when you want to change all letters in a string to uppercase in PHP. It works with…
Echo and print are foundational in displaying output in PHP, and though they might be similar in some ways, they…
The PHP do-while loop is a type of loop that executes a block of code at least once, and then…
Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…