How to Get the Length of an Array in PHP?

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.

  • First Parameter : This is a required Parameter. It identifies the array.
  • Second Parameter: This is an optional Parameter. It is a mode Parameter. You can just put 0 or 1.
    • 1: the count() function will recursively counting all elements of multidimensional arrays.
    • 0: It is default value. In case of 0, the count() function doesn’t count the all elements of the multidimensional arrays.

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.

  • First parameter: this is required parameter and in this parameter the sizeof() function accepts the array.
  • Second Parameter: this is an optional Parameter. It is a mode Parameter. You can put 0 or 1.
    • 1: it will be counting all elements of multidimensional arrays elements.
    • 0: it is default value. In case of 0 it doesn’t count the all elements of multidimensional arrays.

Look at the below example in which we have a fruits array,

$fruits = array("mango","banana","apple","grapes");
echo sizeof($fruits);
// output: 4


Written by
I am Siraj, a results-driven web developer with three years of hands-on experience in both frontend and backend development. My passion for creating seamless digital experiences drives me to continuously innovate and excel in my field.

Share on:

Related Posts

Improved by: Ayaz Ali Shah

Tags: PHP,