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 Courses
php Courses
php Courses
Using PHP count() and sizeof() Functions to Count Array Elements and Object Properties

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: count ( mixed $array , int $mode ) 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:

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));
var_dump(count(null));
var_dump(count(false));
?>

Output (PHP 7.2+):

int(3)
int(0)
int(1)

2. Counting object properties via the Countable interface:

<?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>";
?>

Output shows the array is empty (bool true) while the Countable object is not considered empty (bool false).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend_countobject
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.