PHP Count All Array Elements
The count()
function is used to count all elements in an array.
Syntax
count(array, mode)
array
: Required. Specifies the array to count the number of elements in.mode
: Optional. Specifies the mode of the function. It can take the values0
or1
.0
(default) - The function returns the number of elements in the array.1
- The function counts recursively, i.e., if an element inside the array is an array, then the function counts its elements as well.
Example
$fruits = array("apple", "banana", "orange", array("blueberry", "raspberry"), "mango");
echo count($fruits);
Output
5
Explanation
The above example code counts all the elements in the $fruits
array. It includes the nested array elements as well.
Use
The count()
function can be used to count the number of elements in an array. It can be useful when dealing with arrays of dynamic size.
Important Points
- The
count()
function returns0
if the array is empty. - The
mode
parameter is optional and its default value is0
.
Summary
count()
function is used to count the number of elements in an array.- It takes two parameters - the
array
to count and an optionalmode
. - The default mode is
0
, which returns the number of elements in the array. - The function returns
0
if the array is empty. - It can be useful when dealing with arrays of dynamic size.