PHP Function Reference

PHP sizeof() Function



The PHP sizeof() function returns the number of elements present in the given array, or in an object.

Please note that this function is alias of count() function.

Syntax

sizeof(array, mode)

Parameters

array Required. Specify an array or Countable object.
count Optional. Specify the mode. There are two possible values:
  • 0 - Default - Does not count all elements of multi-dimensional arrays.
  • COUNT_RECURSIVE (or 1) - Counts the elements recursively (counts all the elements of multi-dimensional arrays).

Return Value

Returns the number of elements in the array. If the parameter is neither an array nor an object with implemented Countable interface, 1 is returned. If the parameter is null, 0 is returned.

Exceptions

Throws E_WARNING, if invalid countable types passed to the array parameter. Since PHP 8.0, it throws TypeError on invalid countable types passed to the array parameter.

Example:

The example below shows the usage of sizeof() function.

<?php
$Arr1 = array(10, 20, 30, 40, 50);
$Arr2 = array(10, array(100, 200), array(300, 400));

//counting number of elements in Arr1
echo "Number of Elements in Arr1: ".sizeof($Arr1)."\n";

//counting number of elements in Arr2
echo "Number of Elements in Arr2: ".sizeof($Arr2)."\n";
echo "Number of Elements in Arr2 (Recursively): "
     .sizeof($Arr2, 1)."\n";
?>

The output of the above code will be:

Number of Elements in Arr1: 5
Number of Elements in Arr2: 3
Number of Elements in Arr2 (Recursively): 7

Example:

In the example below, sizeof() function is used to count number of key-value pairs in an associative array.

<?php
$Arr = array("Marry"=>25, 
             "John"=>30, 
             "Jo"=>45, 
             "Kim"=>22);

//counting number of pairs in the array
echo "Number of Pairs in Arr: ".sizeof($Arr)."\n";
?>

The output of the above code will be:

Number of Pairs in Arr: 4

❮ PHP Array Reference