PHP - Array count() Function
The PHP Array count() function is used to return 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:
|
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 below example 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:
In the below example 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