PHP Array count() Function (With Examples)

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

PHP count() Function

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

Syntax

The syntax of the count() function:

count(array, [count_mode])

Parameters

The parameters of the count() 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 count() Function Example 1: Using single dimensional array

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

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

Output

The output of the above example is:

arr1 has 5 elements
arr2 has 5 elements

PHP count() Function Example 2: Using multidimensional array

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

$len = count($students);
print "count value = $len (count_mode is not provided)\n";

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

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

Output

The output of the above example is:

count value = 2 (count_mode is not provided)
count value = 2 (count_mode is set to 0)
count value = 6 (count_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.