How to calculate the PHP array length?
If you want to count the total number of elements or values in an array, you can easily do it by using PHP inbuilt functions called count() or sizeof().
You can find a detailed explanation with the example below that how you can calculate PHP array length.
count(): PHP Array Length For Loop
The Syntax for PHP count() function is very simple.
count(var array_or_countable, mode)
If you don’t know what is an array then please see the detailed explanation of how arrays are created and used in PHP.
The first argument is an array variable that is required to calculate the PHP array length. If the first argument is empty, an empty array or not set, then count() function will return 0.
And, If the variable is specified but its data type is not an array, then, count() function will return 1.
To avoid this, you can use the PHP inbuilt function isset() and check whether an array variable is set or not.
The second argument is optional and can take two values either COUNT_NORMAL or COUNT_RECURSIVE. You can pass the value 0 and 1 instead of COUNT_NORMAL and COUNT_RECURSIVE that will make the same effect.
The default value of the second argument is COUNT_NORMAL if no value passed as the second argument.
Example #1 count() example
$food = array('fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea')); // recursive count echo count($food, COUNT_RECURSIVE); // output 8 // normal count echo count($food); or count($food, COUNT_NORMAL ); // output 2
In the above code block, We have created a multidimensional array.
When we use count function in the RECURSIVE mode as a second argument, Output is 8.
And, when we use count function in the NORMAL mode as a second argument or default mode, Output is 2.
sizeof()— PHP Array Length?
sizeof() is an alias of PHP count() function and accepts the same arguments as count().
If We replace the count() with sizeof() in the above example, the results of both functions will be the same for both functions calls.
Many programmers who come from C language background expect sizeof() to return the amount of memory allocated. But, sizeof() – as described above – is an alias for count() in PHP.
It is advised to always use count() instead of sizeof(). Because there is no guarantee for the alias function if they will exist or not in a future upgrade.
So, you should always consider to maintain code standard as well as avoid to break the application due to the upgraded version.
Want to learn Angular? Click here to start.