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.
Table of Content
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 superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…
The PHP logical operators are operands that can be used to check two or more expressions together. For examples (…
The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…
In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…
PHP array_push lets you add one or more values to the end of an array. It appeared to make adding…
The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…
PHP namespace solves the problem of name conflicts. Different developers may create functions-classes, or constants with the same name. PHP…
PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…
When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…