In this article, you will learn how to count the array elements in PHP. The sizeof() function returns the number of elements in an array.
Note: This function is an alias of count() function.
What is the syntax of the sizeof() function in PHP?
sizeof(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 sizeof() function
Example 1. Count the number of elements in an array.
<?php
$bikes=array("Suzuki","Honda","Yamaha");
echo sizeof($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: " . sizeof($bikes)";
echo "count recursively: " . sizeof($bikes,1);
?>