C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » PHP

How to get the length of the array in PHP?

In this article, we will learn how to get the length of the array in PHP? There are 2 built-in functions that return us the length of the array: 1) count(), 2) sizeof().
Submitted by Abhishek Pathak, on November 07, 2017

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) Using the count() function

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.

Code

<?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
?>

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) Using the sizeof() function

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. Let's consider an example,

Code

<?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
?>

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.





Sponsored Links




COMMENTS