PHP count() function

P
PHP Compact function
PHP current() function

In this article, you will learn how to count the array elements in PHP. The count function returns the number of elements in an array.

What is the syntax of the count function in PHP?

count(array, mode)
ParameterDescription
arrayThe array to count element of – Required
modeCan be either 0 or 1.
When set to 0 – Does not count elements of any subarray (multidimensional array).
When set to 1 – Count the subarray elements (multidimensional array) or count recursively.
PHP count function

Examples of count function

Example 1. Count the number of elements in an array.

<?php
$bikes=array("Suzuki","Honda","Yamaha");
echo count($bikes);
?>

Example 2. Count the number of elements of the multidimensional array (recursively).

<?php
$bikes=array
  (
  "Suzuki"=>array
  (
  "CD150",
  "CD210"
  ),
  "Honda"=>array
  (
  "CD70",
  "125"
  ),
  "Yamaha"=>array
  (
  "YBR"
  )
  );

echo "count: " . count($bikes)";
echo "count recursively: " . count($bikes,1);
?>
PHP Compact function
PHP current() function

Add comment

Tutor Network

Share this

Learn PHP from A to Z