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 to count().

πŸ› οΈ 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 to count() returns 0.
  • 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 null or scalar variables (like integers or strings) to count() will throw a TypeError or 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_RECURSIVE to include nested sub-arrays in multidimensional data structures.
  • Use empty($array) or count($array) === 0 to verify whether an array has elements before iterating.