What is the sizeof() method in PHP?

The sizeof() method is used to find the number of elements present in an array or any Countable objectClasses implementing Countable.

Syntax


int sizeof(array, mode);

Arguments

  • 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 is COUNT_NORMAL.

Code

Example 1

<?php
$arr = array(1,2,3,4,5);
$result = sizeof($arr);
print($result);
?>

Explanation

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.

Example 2

<?php
$array = array(
'odd' => array(1,3,5),
'even' => array(2,4,6)
);
// normal count
echo "Normal count of array : ";
print(sizeof($array, COUNT_NORMAL )); // output 2
echo "\nRecursive count of array : ";
//recursive count
print(sizeof($array, COUNT_RECURSIVE)); // output 8
?>

Explanation

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.

Free Resources