How to Count All Array Elements in PHP

When working with arrays in PHP, you might need to determine the total number of elements within the array.

Counting the elements is a fundamental operation, and PHP provides various methods to achieve this.

In this article, we will explore different ways to count all array elements in PHP.

The PHP count() Function

The simplest and most common way to count all elements in an array is by using the built-in count() function. This function returns the number of elements in an array.

Here's an example:

$fruits = ["apple", "banana", "cherry", "date"];

$count = count($fruits);

echo "Total number of elements: " . $count;

Output:

Total number of elements: 4

In this example, we use count($fruits) to count the number of elements in the $fruits array and store the result in the $count variable. We then print the total number of elements using echo.


The sizeof() function

In PHP, the sizeof() function is an alias for the count() function.

Both sizeof() and count() serve the same purpose: they are used to count the number of elements in an array or the properties in an object. These functions return the same result, making them interchangeable.

Here's an example of using sizeof() to count the elements in an array:

$fruits = ["apple", "banana", "cherry", "date"];

$count = sizeof($fruits);

echo "Total number of elements: " . $count;

Output:

Total number of elements: 4