Last updated on September 6, 2023
To get the length of an array in PHP with the help of the count() function. It counts the array’s element and returns the total count.
count() Function:
count() is built-in function that is used in the PHP for counting the array value. It prints the number of elements of an array. When the array is empty it returns 0.
This function has two parameters: the first is an array and the second is the mode.
Look at below example, in which we have an indexed array containing four elements.
$fruit = array("mango", "banana", "apple", "grapes");
echo count($fruit);
// output: 4
Let’s create a multidimensional array and get the length through count() function. Look at the below example in which we have students array.
// students array
$students = array(
"class_6" => array(
"John",
"Emily"
),
"class_7" => array(
"Michael",
"Sarah"
),
"class_8" => array(
"William "
)
);
echo "Count: " . count($students);
// output: 3
echo "Recursive count: " . count($students,1);
// output: 8
sizeof() Function:
The sizeof() function returns the number of elements in an array. It is an alias of the count() function.
It has two parameters in which first is required and second is optional.
Look at the below example in which we have a fruits array,
$fruits = array("mango","banana","apple","grapes");
echo sizeof($fruits);
// output: 4