PHP count() Function
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(or1) – Counts all elements in the array recursively (useful for multidimensional arrays).
Examples
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);
}
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
