Register Login

PHP count() function with examples

Updated Jan 08, 2020

What is count() function in PHP

PHP count() function is an in-built function available in PHP, which counts and returns the number of elements in an array. It also counts the number of properties in an object.

The count() function may return 0 for the variable, which has been declared with an empty array or for the variable which is not set.

PHP Version

count() function is compatible with PHP version 4 or above

Syntax:

(array_list, mode)

Parameter:

Parameter Type Description
array_list (Required) Array Describes the array or the object whose elements/properties are to be counted
mode (Optional) Integer

Define the mode of the function; Possible values can be 0 or 1

0: Default value. Does not count all the elements of the multi-dimensional array

1: Count all the elements of the multi-dimensional

Return Value:

Number of elements in an array

Example

Below is the simple example of the PHP count() function

<?php
//Declaring and Initializing an array
$productList = array( "PHP Programming", "Programming Fundamentals", "Modern PHP", "PHP and MySQL" );
//Printing the output
echo "Total Number of books is : ".count($productList);
?>

Output

Total Number of books is : 4

Advanced Examples

1) Using PHP count() function with for loop

//Program to print data using count and for loop

<?php

//Declaring and Initializing the array values
$productList = array( "PHP Programming", "Programming Fundamentals", "Modern PHP", "PHP and MySQL" );

//Getting the total number of elements in the array
$totalNumberOfProducts = count($productList);

//for loop for the iteration.
for($i = 0; $i < $totalNumberOfProducts; $i++){
    //Printing the output
    echo "Book at index ".$i." is : ". $productList[$i];
    //Breaking the line
    echo '<br>';
}
?>

Output

Book at index 0 is : PHP Programming
Book at index 1 is : Programming Fundamentals
Book at index 2 is : Modern PHP
Book at index 3 is : PHP and MySQL

2) PHP count function with recursively or passing mode

//Program to print data using count() with recursion

<?php

//Declaring and Initializing the array values
$productList = array(
    'bookNames' => array( "Programming PHP", "Programming Fundamentals", "Modern PHP", "PHP and MySQL" ),
    'bookAuthors' => array( "Rasmus Lerdorf", "S. K. Jha", "Josh Lockhart", "Joel Murach, Ray Harris" )
    );
//Printing the total number of elements in the array without recursion
echo "Total number of elements : ". count($productList,0);
//Breaking the line
echo "<br>";
//Printing the total number of elements in the array with recursion
echo "Recursively count elements total is : ". count($productList,1);
?>

Output:

Total number of elements : 2
Recursively count elements total is : 10

 


×