PHP Tutorial

PHP Examples

PHP Practice

PHP Array sizeof() Function (With Examples)

In this tutorial, we will learn about the PHP sizeof() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP sizeof() Function

The sizeof() function is an alias of count() function, it is used to get the total number of elements of an array.

Syntax

The syntax of the sizeof() function:

sizeof(array, [count_mode])

Parameters

The parameters of the sizeof() function:

  • array is the name of an input array
  • count_mode is an optional parameter and it's default value is 0, it has two values:
    • 0: It does not count all elements of a multidimensional array
    • 1: It counts all elements of a multidimensional array

Return Value

The return type of this method is int, it returns the number of elements in value.

Sample Input/Output

Input:
$arr1 = array("101", "102", "103", "104", "105");

Output:
arr1 has 5 elements

PHP sizeof() Function Example 1: Using single dimensional array

<?php    
$arr1 = array("101", "102", "103", "104", "105");
$arr2 = array("Amit", "Abhishek", "Prerana", "Aleesha", "Prem");

$len = sizeof($arr1);
print ("arr1 has $len elements\n");
$len = sizeof($arr2);
print ("arr2 has $len elements\n");	
?>

Output

The output of the above example is:

arr1 has 5 elements
arr2 has 5 elements

PHP sizeof() Function Example 1: Using multidimensional array

<?php
$students = array(
    "101" => [
        "name" => "Amit",
        "age" => 21,
    ],
    "102" => [
        "name" => "Abhi",
        "age" => 20,
    ],
);

$len = sizeof($students);
print "sizeof value = $len (sizeof_mode is not provided)\n";

$len = sizeof($students, 0);
print "sizeof value = $len (sizeof_mode is set to 0)\n";

$len = sizeof($students, 1);
print "sizeof value = $len (sizeof_mode is set to 1)\n";
?>

Output

The output of the above example is:

sizeof value = 2 (sizeof_mode is not provided)
sizeof value = 2 (sizeof_mode is set to 0)
sizeof value = 6 (sizeof_mode is set to 1)

To understand the above examples, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.