The Wayback Machine - https://web.archive.org/web/20250114132213/https://www.geeksforgeeks.org/php-count-function/
Open In App

PHP count() Function

Last Updated : 20 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. 

Syntax:

count($array, mode)

Parameters: The function generally takes one parameter that is the array for which the elements is needed to be counted. But in addition, the function can take a parameter mode which tells the function to count element in which normal or recursive mode.

  1. $array (mandatory) : Refers to the array, whose elements are needed to be counted.
  2. mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False.

Return Values: The function returns the number of elements in an array. Below programs will help in understanding the working of count() function. 

Program 1: Counting normally, that is passing mode as 0 or not passing the parameter mode. 

PHP




<?php
  
// PHP program to illustrate working of count()
$array = array("Aakash", "Ravi", "Prashant", "49", "50");
  
print_r(count($array));
  
?>


Output:

5

Program 2: Counting recursively or passing mode as 1. 

PHP




<?php
  
// PHP program to illustrate working of count()
$array = array('names' => array('Aakash', 'Ravi', 'Prashant'),
               'rollno' => array('5', '10', '15'));
  
// recursive count - mode as 1
echo("Recursive count: ".count($array,1)."\n");
  
// normal count - mode as 0
echo("Normal count: ".count($array,0)."\n");
  
?>


Output:

Recursive count: 8
Normal count: 2

Reference: http://php.net/manual/en/function.count.php


Become a Full-Stack Developer and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article

Similar Reads

three90RightbarBannerImg