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.
Add items to see how the count() function reacts instantly.
count($myArray) = 0count() returns the total number of elements in an arraysizeof() is an alias of count()
// Syntax using count()
count($array);
// Syntax using sizeof()
sizeof($array);
// Counting elements in an indexed array
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo count($fruits);
?>
The array contains three elements, so the count() function returns 3.
// Counting key-value pairs in an associative array
<?php
$ages = array("Peter" => 35, "John" => 30, "Doe" => 25);
echo count($ages);
?>
// 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.
count() for better readabilityCOUNT_RECURSIVE for nested arrays when required