PHP Tutorial - PHP count() Function






Definition

The count() function returns the number of elements in an array.

Syntax

PHP count() Function has the following syntax.

count(array,mode);

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to count
modeOptional.Specifies the mode.

Possible values for mode:

  • 0 - Default. Does not count multidimensional arrays
  • 1 - Counts the array recursively for the elements of multidimensional arrays




Example 1

Count element in an array


<?php
$cars=array("A","B","C","java2s.com");
echo count($cars);
?>

The code above generates the following result.

Example 2

Count the array recursively:


<?php/*  ww  w .j a  va  2  s.co m*/
$a=array(
  "Java"=>array("int","double"),
  "CSS"=>array("height","width"),
  "PHP"=>array("form")
); 

echo "Normal count: " . count($a)."\n";
echo "Recursive count: " . count($a,1);
?>

The code above generates the following result.