The sizeof()
method is used to find the number of elements present in an array or any
int sizeof(array, mode);
array
: The array for which the number of elements is to be determined.
mode
: An optional argument that specifies how values are counted. mode
has two possible values:
COUNT_NORMAL
or 0
: Only the first level elements are counted in a multi-dimensional array.
COUNT_RECURSIVE
or 1
: All the elements in a multi-dimensional array are recursively counted.
The default value for the
mode
argument isCOUNT_NORMAL
.
<?php$arr = array(1,2,3,4,5);$result = sizeof($arr);print($result);?>
In the code above, we create an array and call the sizeof()
method on the array, which will return the size of the array. In our case, the sizeof()
method will return 5
.
<?php$array = array('odd' => array(1,3,5),'even' => array(2,4,6));// normal countecho "Normal count of array : ";print(sizeof($array, COUNT_NORMAL )); // output 2echo "\nRecursive count of array : ";//recursive countprint(sizeof($array, COUNT_RECURSIVE)); // output 8?>
In the code above, we create a multi-dimensional array.
sizeof($array, COUNT_NORMAL )
We call the sizeof()
method with COUNT_NORMAL
as the value for the mode
argument. This will only count the number of elements in a single level. So, we will get 2
as a result.
sizeof($array, COUNT_RECURSIVE)
We call the sizeof()
method with COUNT_RECURSIVE
as the value for the mode
argument. This will count the number of elements in an array recursively. So, we will get 8
as a result.