How to get the length of the array in PHP?

By Abhishek Pathak Last updated : December 20, 2023

Problem statement

Given a PHP array, we have to find its length using different methods.

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

PHP - Getting Array Length

Arrays are common data type in PHP and we require it many times to store similar data type in one entity. As a PHP developer it is important to know the operations on array, such as getting its length. Using the built-in PHP functions we can get the length of the array.

There are 2 built-in functions that return us the length of the array:

  1. count()
  2. sizeof()

We'll discuss them in the following section...

1. Finding length of a PHP array using count() method

The count() function takes in the array parameter and returns the count of the number of element present in that array. The count() function is more popular and widely used that the other function. It basically consists of loop that has a counter element which traverses the whole array and returns the final value, i.e. the length of the array.

PHP code to get array length using count()

<?php
  //Create a hobbies array
  $hobbies = array('Painting', 'Coding', 'Gaming', 'Browsing');

  //Get the number of elements in hobbies array
  $hobby_count = count($hobbies);

  //Display the hobbies count
  echo $hobby_count; // Output: 4
?>

Output

4

Explanation

In this code, we create the $hobbies variable which consists of 4 elements. Then we have another variable hobby_count which stores the result of the count() operation applied on the hobbies array which is the number of elements in it. Then we simply display the hobby_count variable which shows the number of elements in the hobbies array.

2. Finding length of a PHP array using sizeof() method

The sizeof() is the alias of the count() method that returns the number of elements in the array just like the count() function. It is not common with developers since it confuses with the sizeof operator in C/C++.

PHP code to get array length using sizeof()

<?php
  //Create a hobbies array
  $hobbies = array('Painting', 'Coding', 'Gaming', 'Browsing');

  //Get the number of elements in hobbies array
  $hobby_count = sizeof($hobbies);

  //Display the hobbies count
  echo $hobby_count; // Output: 4
?>

Output

4

Explanation

As we can see, the result is same, since these functions are the alias of each other. While it is recommended that you use the first function to return the length of the array, it is good to know that there are various methods to do it.

Hope you like the article. Please share your thoughts in the comments.

PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.