How to Find Length of Associative Array Using PHP

Last Updated on January 9, 2021 by Roshan Parihar

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

You can also use the PHP sizeof() that gives the same result of the size of an array in the output. The loop in PHP can also be used to perform iteration and count the number of elements in an array. However, it requires to parse through all the elements to get the size.

The associative array is the array that contains items with manually assigned keys of string type and its values. Each key is manually assigned by the users. Let’s find out how to get the length of an associative array with the examples given below:

Find Length of Associative Array Using PHP count()

To get the length of an associative array, you can use the PHP count(). It takes an argument as the associative variable that contains the elements of array in PHP. The function checks the number of elements in the array and prints it in the output as given below:

Output

3

The above example contains an associative array with 3 elements inside it. The output shows that the length of an associative array is 3.

Get Size of Array with PHP sizeof()

This is another method and works the same as the function uses above. The PHP sizeof() function takes an argument as the associative array variable. It checks the size of the array that is the number of items inside the array.

Output

4

The above example contains 4 items inside the array. The output shows that the size of an associative array is 4.

Using Foreach Loop of PHP

In addition to the above al methods, you also use the PHP foreach loop to get the size of an associative array. The loop takes an argument as the associative variable and the pair of key-value as $key => $value. However, you have to initiate a variable to zero (0) and use it inside loop with increment operator (++) to count the number of items inside an associative array. The loop traverses through all the elements to find the number of items as given in the example below:

Output

3

The above example shows that there are 3 elements in the array that you have to find in the output.

All the methods are given above are useful to count the number of items. However, the first two methods that use count() and sizeof() are faster than the last methods that use the loop that takes time to traverse.

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.