Array Functions
Advertisements

PHP sizeof() Function

Topic: PHP Array ReferencePrev|Next

Description

The sizeof() function count all elements in an array (alias of count() function).

The following table summarizes the technical details of this function.

Return Value: Returns the number of elements in an array.
Changelog: Since PHP 7.2.0 this function yield a warning on invalid countable types.
Version: PHP 4+

Syntax

The basic syntax of the sizeof() function is given with:

sizeof(array, mode);

The following example shows the sizeof() function in action.

<?php
// Sample array
$cars = array("Audi", "BMW", "Mercedes", "Volvo");
    
// Display array elements count
echo sizeof($cars);
?>

Parameters

The sizeof() function accepts two parameters.

Parameter Description
array Required. Specifies an array or countable object.
mode Optional. If it is set to COUNT_RECURSIVE (or 1), sizeof() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
 

Note: The sizeof() function may return 0 for a variable that isn't set, or has been initialized with an empty array. Use isset() function to test if a variable is set.


More Examples

Here're some more examples showing how sizeof() function basically works:

The following example demonstrates how to count all the elements in a multidimensional array recursively using the sizeof() function. Let's try it out and see how it works:

<?php
// Sample array
$cars = array(
    "Audi" => array("RS7", "A8"), 
    "BMW" => array("Z4", "X7", "M8"), 
    "Mercedes" => array("GLA", "GLS"),
    "Volvo" => array("XC90")
);

// Getting normal count
echo sizeof($cars); // Prints: 4   

// Getting recursive count
echo sizeof($cars, 1); // Prints: 12
?>
Advertisements
Bootstrap UI Design Templates