Count Array Length In PHP Tutorial with Examples – POFTUT

Count Array Length In PHP Tutorial with Examples

PHP programming language provides the count(), sizeof() functions and foreach in order to count the elements in an array. The array can be a single dimension or multidimensional array.

count() Function Syntax

The count() function is the most popular way to count array length.

  • ARRAY is the array we want to count which can be a simple array or multidimensional array
  • MODE is the count operating mode which can be default which is represented as 0 or recursive 1. MODE parameter is optional and if it is not provided it will be assumed as 0 by default.

Array Length with count() Function

We can use count() function by providing the array we want to get the length. The array is a simple array that provides the car numbers like below.

Array Length with count() Function

Array Length with count() Function

As we can see the $food array has only two elements in the first level. In the second level, there are more elements. So simple usage of count() function will return 2 as element count as it is not recursive by default.

Recursive/Multidimensional Array Length with count() Function

If the given array is multidimensional we have used some extra parameter with the count() function. We will provide the 1 as a second parameter to the count() function.

Recursive/Multidimensional Array Length with count() Function

Recursive/Multidimensional Array Length with count() Function

We can see the by providing the recursive counting the count of the $food array is printed as 8 .

Array Length with sizeof() Function

sizeof() function is used to count the array elements. Actually sizeof() function is an alias of the count() function. It is created in the old days of the PHP where similar to the C programming language sizeof() function. It is preserved as backward compatibility but using sizeof() function is not a good practice especially for the feature.

Array Length with sizeof() Function

Array Length with sizeof() Function

We can see from the output that sizeof() function does not count multidimensional arrays 2 level arrays. The size of the $food array is printed as 2.

Array Length with foreach statement

foreach is an enumeration statement used to enumerate the given array or list. We can also use foreach in order to count given array but this will require some effort if the array is multidimensional.

Array Length with foreach statement

Array Length with foreach statement

Leave a Reply

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

Enjoy this blog? Please spread the word :)