← Back to Chapters

PHP Array Count & Sizeof Function

? PHP Array Count & Sizeof Function

? Quick Overview

In PHP, both the count() and sizeof() functions are used to determine the number of elements in an array. Both functions return the same result and can be used interchangeably. The count() function is preferred because it is more descriptive and commonly used.

? Interactive Array Lab

Add items to see how the count() function reacts instantly.

 
PHP Equivalent: count($myArray) = 0

? Key Concepts

  • count() returns the total number of elements in an array
  • sizeof() is an alias of count()
  • Works with indexed and associative arrays
  • Supports recursive counting for nested arrays

? Syntax / Theory

? View Code Example
// Syntax using count()
count($array);

// Syntax using sizeof()
sizeof($array);

? Code Example (Indexed Array)

? View Code Example
// Counting elements in an indexed array
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo count($fruits);
?>

? Output / Explanation

The array contains three elements, so the count() function returns 3.

? Code Example (Associative Array)

? View Code Example
// Counting key-value pairs in an associative array
<?php
$ages = array("Peter" => 35, "John" => 30, "Doe" => 25);
echo count($ages);
?>

? Interactive Concept (Recursive Count)

? View Code Example
// Using COUNT_RECURSIVE for multidimensional arrays
<?php
$data = array(
    "Books" => array("PHP", "Python"),
    "Editors" => array("VS Code", "Vim")
);
echo count($data, COUNT_RECURSIVE);
?>

This counts both the top-level elements and all nested elements inside the array.

? Use Cases

  • Controlling loops dynamically
  • Validating array size before processing
  • Handling dynamic form or API data
  • Managing records from databases

✅ Tips & Best Practices

  • Prefer count() for better readability
  • Use COUNT_RECURSIVE for nested arrays when required
  • Always ensure the variable is an array before counting

? Try It Yourself

  • Create an array of favorite movies and count them
  • Build an associative array of employees and salaries
  • Experiment with multidimensional arrays and recursive counting