In this article, you will learn how to count the array elements in PHP. The count function returns the number of elements in an array.
What is the syntax of the count function in PHP?
count(array, mode)
Parameter | Description |
---|---|
array | The array to count element of – Required |
mode | Can be either 0 or 1. When set to 0 – Does not count elements of any subarray (multidimensional array). When set to 1 – Count the subarray elements (multidimensional array) or count recursively. |
Examples of count function
Example 1. Count the number of elements in an array.
<?php
$bikes=array("Suzuki","Honda","Yamaha");
echo count($bikes);
?>
Example 2. Count the number of elements of the multidimensional array (recursively).
<?php
$bikes=array
(
"Suzuki"=>array
(
"CD150",
"CD210"
),
"Honda"=>array
(
"CD70",
"125"
),
"Yamaha"=>array
(
"YBR"
)
);
echo "count: " . count($bikes)";
echo "count recursively: " . count($bikes,1);
?>