How to Get the Length of an Array in PHP: Complete Guide

In PHP, working with arrays is fundamental for handling lists of data. One common task is determining the length of an array, which refers to the number of elements it contains. In this guide, we will explore different ways to get the length of an array in PHP, along with practical examples and best practices.

1. Using count() to Get the Length of an Array in PHP

The most common method to get the length of an array in PHP is by using the built-in count() function. This function counts the number of elements in an array and returns the result.

Syntax:

php

count(array, mode);
  • array: The array whose length you want to determine.
  • mode: (Optional) Set this to COUNT_RECURSIVE to count elements in multi-dimensional arrays.

Example:

php

$array = [1, 2, 3, 4, 5];
$length = count($array);
echo "The length of the array is: " . $length;

Output:

C
The length of the array is: 5
In this example, the count() function returns the total number of elements in the array, which is 5.

2. Using sizeof() to Get the Length of an Array in PHP

The sizeof() function is an alias of count() in PHP. It works in exactly the same way and can be used interchangeably with count().