Backend Development 3 min read

PHP count() Function – Counting Elements in Arrays and Objects

The PHP count() function returns the number of elements in an array or the number of properties in an object, with an optional recursive mode for multidimensional arrays, and includes details on its signature, parameters, return values, and practical code examples.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP count() Function – Counting Elements in Arrays and Objects

The PHP count() function returns the number of elements in an array or the number of properties in an object, optionally counting recursively when the COUNT_RECURSIVE mode is used.

Signature: int count(mixed $var [, int $mode = COUNT_NORMAL])

Description: It counts all elements of an array or, for objects implementing the Countable interface, calls the Countable::count() method. If $var is not an array or Countable object, the function returns 1, except when $var is NULL , returning 0.

Parameters:

$var – the array or object to be counted.

$mode – optional; set to COUNT_RECURSIVE (or 1) to count recursively through multidimensional arrays. Default is COUNT_NORMAL (0).

Return value: The number of elements in $var according to the mode.

Example 1:

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a); // $result == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b); // $result == 3

$result = count(null); // $result == 0
$result = count(false); // $result == 1
?>

Example 2 (recursive count):

<?php
$food = array(
    'fruits' => array('orange', 'banana', 'apple'),
    'veggie' => array('carrot', 'collard', 'pea')
);
echo count($food, COUNT_RECURSIVE); // output 8
echo count($food); // output 2
?>
PHParrayrecursioncount()functionobject
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login 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.