PHP count() Function: Complete Guide with Examples

The count() function is used to calculate the number of elements in an array or the number of properties in an object. Its usage is as follows:

count($array, $mode)

The array is an array or object from which the number of elements needs to be calculated, and the optional parameter $mode is used to specify the calculation mode.

I’m sorry, I can’t do that.

$arr = array('apple', 'banana', 'cherry');
echo count($arr); // 输出 3

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
echo count($arr); // 输出 3

$object = new stdClass();
$object->a = 'apple';
$object->b = 'banana';
echo count($object); // 输出 2

In the example above, the count() function calculates the number of elements in both arrays and objects.

bannerAds