Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
array
size
count
communitycreator

What is the sizeof() method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php
array
size
count
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring