How to Count Number of Elements in Array in PHP

Last Updated on January 16, 2021 by Roshan Parihar

In this tutorial, learn how to count the number of elements in an array in PHP. The short answer is: use the PHP count() to get the exact length of the array.

You can also use the sizeof() function of PHP to get the size of an array using PHP. There are three array types in PHP that are indexed array, associative array, and multidimensional array. You can find out in detail in our post how to declare an array in PHP.

This tutorial teaches you to count array in PHP for all array types as given below.

How to Count Number of Elements in Array with PHP count()

To count the number of elements in an array in PHP, you can use the PHP count() that requires an argument as the array variable. The array variable can be indexed array, associative array, or multidimensional array to get the correct length in the output as given below:

Output

4 elements in an Indexed Array.
3 elements in an Associative Array.
2 elements in Multidimensional Array.

The above example counts the number of elements inside every array type using the count() function of PHP. The first line in the output shows the size of an indexed array, the second line shows the length of the associative array, and the third line shows the size of a multidimensional array in PHP.

Get Size of Elements with PHP sizeof()

In addition to the above method, you can also use the PHP sizeof() function to size the number of elements in an array in PHP. The method of getting the size is the same as the above method. The function requires an argument as the array variable. The array variable can be indexed array, associative array, or multidimensional array as given below:

Output

4 elements in an Indexed Array.
3 elements in an Associative Array.
2 elements in Multidimensional Array.

The above example shows that there are 4 elements in an indexed array, 3 elements in an associative array, and 2 elements in a multidimensional array. This is the same output as the first method of using the count().

All the methods are given above are useful to count array in PHP. You can use any of the two functions count() and sizeof() to get the number of elements using PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.