PHP count() function

PHP count() function

The count() function in PHP is used to count all elements in the specified array or something in an object.

Syntax

count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  

Parameter

array_or_countable(required)– This parameter represents the input array or countable object.

mode(optional)- This parameter is used to specify the mode. The possible mode values are as follows:

  • If it is set to integer value 0 (default value), it does not count all elements of multidimensional arrays
  • If set to integer value 1, it counts all the elements of multidimensional arrays recursively.

Return

This function returns the number of elements in the array.

It returns 1, if the parameter “array_or_countable” is neither an array nor an object.

It returns 0, if array_or_countable is NULL.

Example 1

<?php
 $fruits = array("Mango", "Banana", "Strawberry", "Apple");
 print_r($fruits);
 //will return the total number of the elements present in the array
 $count= count($fruits);
 echo("The count of the array is ".$count);
 ?> 

Output

Array
 (
     [0] => Mango
     [1] => Banana
     [2] => Strawberry
     [3] => Apple
 )
 The count of the array is 4 

Example 2

<?php
 $a[0] = 1;
 $a[1] = 3;
 $a[2] = 5;
 //counting the number of elements in an array
 var_dump(count($a));//will return int(3)
 ?> 

Output

int(3)

Example 3

<?php
 //initializing the array inside array
 $students=array (
   "Reema"=>array ( "Roll No"=>"15CS1029", "Coruse"=>"Btech CSE" )
   ,
   "Shivam"=>array( "Roll No"=>"15CS1019", "Coruse"=>"Btech Civil")
   , 
   "Monica"=>array( "Roll No"=>"15CS1022", "Coruse"=>"Btech Mechanical") 
  );
 //counting all the elements of multidimensional arrays
 echo "Recursive count: " . count($students,1);
 ?> 

Output

Recursive count: 9

Example 4

<?php
 $a[0] = 1;
 $a[1] = 3;
 $a[2] = 5;
 //counting the number of elements in an array
 var_dump(count(null));//will throw an error as the parameter is null
 ?> 

Output

PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /workspace/Main.php on line 6

Example 5

<?php
 $a[0] = 1;
 $a[1] = 3;
 $a[2] = 5;
 //counting the number of elements in an array
 var_dump(count(false));//will throw an error as the parameter is false
 ?> 

Output

PHP Warning:  count(): Parameter must be an array or an object that implements Countable in /workspace/Main.php on line 6