The count()
function in PHP is used to count all elements in an array or something in an object. It returns the number of elements in the array.
🔹 Syntax:
count(array, mode)
array
– Required. The array or object to count.
mode
– Optional. Can be set to:
COUNT_NORMAL
(default) – Does not count elements in multidimensional arrays.
COUNT_RECURSIVE
(or 1
) – Counts all elements in the array recursively (useful for multidimensional arrays).
🔹 Example 1: Basic array count
$fruits = ["apple", "banana", "orange"];
echo count($fruits); // Output: 3
🔹 Example 2: Associative array
$user = [
"name" => "John",
"email" => "john@example.com",
"age" => 30
];
echo count($user); // Output: 3
🔹 Example 3: Multidimensional array with normal count
$products = [
["name" => "Laptop", "price" => 500],
["name" => "Phone", "price" => 300]
];
echo count($products); // Output: 2
🔹 Example 4: Multidimensional array with recursive count
$products = [
["name" => "Laptop", "price" => 500],
["name" => "Phone", "price" => 300]
];
echo count($products, COUNT_RECURSIVE); // Output: 6
Explanation: There are 2 main elements, each with 2 sub-elements → 2 (outer)
+ 2*2 (inner)
= 6
.
🔹 Example 5: Count on empty array
$empty = [];
echo count($empty); // Output: 0
🔹 Example 6: Count on a non-array
$str = "Hello";
echo count($str); // Output: 1 (Not recommended)
🔸 count()
can return 1 even for non-arrays. Safer to check is_array()
before using count()
.
✅ Tips:
- Always ensure the variable is an array before using
count()
:
if (is_array($myVar)) {
echo count($myVar);
}