How to Count All the Array Elements with PHP

  1. Using the count() Function
  2. Using the sizeof() Function

Suppose, you have an array that includes several elements, and you need to count all of them with the help of PHP. Here, we will represent two handy methods to do that.

Using the count() Function

To count all the current elements inside an array. In the case of an empty array, it will return 0.

The syntax is shown below:

count($array, mode)
If the optional mode parameter is set to COUNT_RECURSIVE (or 1),count () will recursively count the number of elements inside the array. That is, especially, useful for counting all the elements of multidimensional arrays.

And, here is an example:

<?php
// PHP program for counting all the elements 
// or values inside an array 

// Using the count() function 
$array = [
  "W3docs1",
  "W3docs2",
  "W3docs3",
  "1",
  "2",
  "3"
];

echo "Count first array elements: " . count($array) . "\n";

$array = [
  'names' => [
    "W3docs1",
    "W3docs2",
    "W3docs3"
  ],
  'rank' => [
    '1',
    '2',
    '3'
  ]
];

echo "Recursive count: " . count($array, 1) . "\n";
echo "Normal count: " . count($array, 0);

?>

After using the count() function, you will have the following output:

  Count first array elements: 6
  Recursive count: 8
  Normal count: 2

Using the sizeof() Function

This function is used for counting the number of the elements inside an array or another countable object.

The syntax used for this function is as follows:

sizeof($array, mode)
Sizeof() is the alias of count().

To be more precise, let’s see an example:

<?php
// PHP program for counting all the elements 
// or values inside an array 

// Use of sizeof() function 
$array = [
  "W3docs1",
  "W3docs2",
  "W3docs3",
  "1",
  "2",
  "3"
];

echo "Count second array elements: " . sizeof($array) . "\n";

$array = [
  'names' => [
    "W3docs1",
    "W3docs2",
    "W3docs3"
  ],
  'rank' => [
    '1',
    '2',
    '3'
  ]
];

echo ("Recursive count: " . sizeof($array, 1) . "\n");
echo ("Normal count: " . sizeof($array, 0) . "\n");

?>

After using the sizeof() function, you will have the following output:

  Count second array elements: 6
  Recursive count: 8
  Normal count: 2

Above, we represented two helpful functions that can be used for counting the elements of an array in PHP. Both the functions are easy in usage and can make you improve your work.


Do you find this helpful?

Related articles