PHP length of array-How to count all elements or values in array

Summary: in this article, you will learn How to get the PHP length of array or How to count all elements or values in an array in PHP. Let’s understand the PHP length of arry with an example.

Answer: PHP length of array- Use sizeof() or count() function

You can simply use the PHP sizeof() or count() function to get the number of elements or values in an array or to calculate the PHP length of array. The php sizeof() and count() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that is not set.

Output:
7
7
PHP length of array explanation:

as you can see the above output, when use count function, it will return 7, means that the array size is 7 and when we use sizeof fuction, the output come 7(the array size is 7). so, you can use both fuction to get the length of array.

.
Note: Returns the number of elements in value. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if the value is null, 0 will be returned.

The Difference Between count and sizeof.

  • The PHP count function and the PHP sizeof function do the exact same thing. In fact, sizeof is just an alias of the count function.
  • Personally, I would be recommended that you stick to using the PHP count function. this can be as a result of different programmers may expect the sizeof function to return the size of the array in bytes/memory.
  • Note that as of PHP 7.2, the count function will emit an E_WARNING error if you offer it with a variable that is not an array or a Countable object.

Conclusion:

in this article, you have learned How to use count() and sizeof() PHP function to get the PHP length array and the difference between the both function. I hope you will enjoy it!.