PHP
π’ PHP count() Function: Counting Array Elements
The count() function in PHP is a built-in utility used to calculate and return the total number of elements inside an array or countable object.
-
Key Concept: Knowing the size of an array is essential for executing control loops, validating database query results, and checking empty data structures. Alias:
sizeof()performs identically tocount().
π οΈ Basic Syntax & Usage
Pass any indexed or associative array directly to count() to retrieve the exact element count as an integer:
PHP
// Basic Indexed Array
$languages = ["PHP", "JavaScript", "Python", "HTML", "CSS"];
$totalLanguages = count($languages);
echo "Total Items: " . $totalLanguages; // Outputs: Total Items: 5
// Basic Associative Array
$user = [
"username" => "john_doe",
"email" => "john@example.com",
"role" => "Admin"
];
echo "Total Fields: " . count($user); // Outputs: Total Fields: 3
π Recursive Counting (Multidimensional Arrays)
By default, count() performs a top-level count. To count all elements within nested/multidimensional arrays recursively, pass COUNT_RECURSIVE (or 1) as the second parameter:
PHP
$categories = [
"Web" => ["HTML", "CSS", "PHP"],
"Database" => ["MySQL", "PostgreSQL"]
];
// Normal Count (Only top-level keys)
echo count($categories); // Outputs: 2
// Recursive Count (Top-level keys + nested elements)
echo count($categories, COUNT_RECURSIVE); // Outputs: 7 (2 keys + 5 nested elements)
π Core Usage Rules & Best Practices
-
1. Empty Array Safety: An empty array
[]passed tocount()returns0. -
2. Loop Optimization: Store the output of
count()in a variable before running heavy loops (e.g.,for ($i = 0; $i < $total; $i++)) to prevent recalculating array size on every iteration. -
3. Non-Countable Warning: Passing
nullor scalar variables (like integers or strings) tocount()will throw aTypeErroror Warning in modern PHP versions (PHP 7.2+).
π Mode Parameter Reference
| Parameter Mode | Constant / Value | Behavior |
|---|---|---|
| COUNT_NORMAL | 0 (Default) |
Counts only first-level elements, ignoring nested array children. |
| COUNT_RECURSIVE | 1 |
Recursively counts all elements in nested multidimensional arrays. |
-
π Short Summary
-
count()measures array length and counts total contained elements. -
Use
COUNT_RECURSIVEto include nested sub-arrays in multidimensional data structures. -
Use
empty($array)orcount($array) === 0to verify whether an array has elements before iterating.
