Find Array Length in PHP

There are two main inbuilt functions, count() and sizeof(), to find an array length in PHP. There are other ways to count array length in PHP, but inbuilt functions are a more straight forward and effortless approach to find array length.

Count Array Length in PHP

count() and sizeof() both functions are inbuilt in PHP in all versions. Evenmore, sizeof() function is alias of count() function. However count() function is quite popular than sizeof(), still there is no difference between both.

Find Array length using Count() Function

Syntax

count($array_name, mode);

Count() function is the most popular function to find array length in PHP. It has the feature of finding the length of an array in two different modes.

What Is Mode and Types of Mode in PHP Count()/Sizeof() Function?

A mode is a flag/parameter in count()/sizeof() function, which indicates to count the specified array length till which depth. There are two modes available in the count() function.

  1. COUNT_NORMAL – This flag indicates the count() function to find and return the array’s length at depth 0 only.
  2. COUNT_RECURSIVE – This flag indicates the count() function to find and return the length of the array to the total depth

Example

<?php
    $arr = array("Crypto"=>array("Bitcoin", "Ethereum", "Litecoin"),"Currecy"=>array("USD", "Pound", "Rupee"));
    echo "Count Default/Normal ".count($arr);
    echo "<br>";
    echo "Count Recursive ".count($arr, COUNT_RECURSIVE);
?>

Output

Count Default/Normal 2
Count Recursive 8

Note: COUNT_NORMAL is default parameter in count() function.

Find Array length using Sizeof() Function

Syntax

sizeof($array_name, mode);

sizeof() function returns the exact output as count() function. It has the same mode feature with two parameters, as mentioned above.

Example

<?php
    $arr = array("Crypto"=>array("Bitcoin", "Ethereum", "Litecoin"),"Currecy"=>array("USD", "Pound", "Rupee"));
    echo "Count Default/Normal ".sizeof($arr);
    echo "<br>";
    echo "Count Recursive ".sizeof($arr, COUNT_RECURSIVE);
?>

Output

Count Default/Normal 2
Count Recursive 8

Conclusion

I hope now you have a complete understanding of count() and sizeof() functions in PHP to count the length of an array in PHP.

Happy Coding πŸ™‚

Leave a Reply

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

Read previous post:
onclick event in php
How to Set Onclick Function in PHP

Onclick event is one of the most used events in any user interface. As all events on the website are...

Close