Using PHP count() and sizeof() Functions to Count Array Elements and Object Properties
The article explains PHP's count() function (alias sizeof()), its syntax, parameters—including the optional COUNT_RECURSIVE mode—and demonstrates how to count array elements and object properties with practical code examples, highlighting return values and behavior with null or non‑countable inputs.
PHP provides the count() function (alias sizeof() ) to obtain the number of elements in an array or the number of properties in an object.
Syntax:
<code>count ( mixed $array , int $mode )</code>Parameters:
$array : an array or a Countable object.
$mode (optional): set to COUNT_RECURSIVE (or 1 ) to count recursively.
Return value: the number of elements. If the argument is neither an array nor a Countable object, the function returns 1 ; if $array is null , it returns 0 .
Usage examples:
1. Counting array elements:
<code><?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));
var_dump(count(null));
var_dump(count(false));
?></code>Output (PHP 7.2+):
<code>int(3)
int(0)
int(1)</code>2. Counting object properties via the Countable interface:
<code><?php
class C implements Countable {
public function count() {
return 0;
}
}
$a = [];
var_dump($a);
echo 'array is empty: ';
var_dump(empty($a));
echo "<br>";
$c = new C;
var_dump($c);
echo "<br>";
echo 'Countable is empty: ';
var_dump(empty($c));
echo "<br>";
?></code>Output shows the array is empty (bool true) while the Countable object is not considered empty (bool false).
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.