PHP Tutorial PHP Advanced PHP Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

PHP - Array count() Function



The PHP Array count() function returns the number of elements present in the given array.

Syntax

count(array, mode)

Parameters

array Required. Specify an array.
count Optional. Specify the mode. There are two possible values:
  • 0 - Default - Does not count all elements of multidimensional arrays.
  • 1 or COUNT_RECURSIVE - Counts the elements recursively (counts all the elements of multidimensional arrays).

Return Value

Returns the number of elements in the array. If the parameter is neither an array nor an object with implemented Countable interface, 1 is returned. If the parameter is null, 0 is returned.

Exceptions

throws E_WARNING, if the array contains itself more than once.

Example:

The example below shows the usage of count() function.

<?php
$Arr = array(10, 20, 30, 40, 50);

//counting the number of elements in the array
$x = count($Arr);

echo "Number of elements in Arr: $x";
?>

The output of the above code will be:

Number of elements in Arr: 5

Example:

The example below shows the usage of count() function with an associative array.

<?php
$Arr = array("Marry"=>25, "John"=>30, "Jo"=>45, "Kim"=>22);

//counting the number of elements in the array
$x = count($Arr);

echo "Number of elements in Arr: $x";
?>

The output of the above code will be:

Number of elements in Arr: 4

❮ PHP Array functions

5