Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to count all elements or values in an array in PHP?

Answer: Using PHP count() and sizeof() function.

PHP offers some built-in functions that can be used to count the number of elements within an array. Most of the time, we can manually count the number of elements within the array but what if there are thousands of arrays. For this PHP offers count() and sizeof() function. Both the function is used to count the number of elements within the array.

The count() and sizeof() function returns 0 for the variable that has been initialized with the empty array.

Example: Using count() function

The count() function is used to count the number of elements within the array. This function returns 0 when the array is empty. In the given example, we have used the count() function to find the number of elements within the array.

<!DOCTYPE html>
<html>
<head>
	<title>count all elements or values in an array</title>
</head>
<body>
	<?php
	$lang = array("HTML", "CSS", "JavaScript", "Bootstrap", "PHP"); 
	echo count($lang);
	?>
</body>
</html>

Output


5

Example: Using sizeof() function

The sizeof() function is also used to count the number of elements within the array. In the given example, we have specified the number of elements within the array using the sizeof() function.

<!DOCTYPE html>
<html>
<head>
	<title>count all elements or values in an array</title>
</head>
<body>
	<?php
	$lang = array("HTML", "CSS", "JavaScript", "Bootstrap", "PHP"); 
	echo sizeof($lang);
	?>
</body>
</html>

Output


5

Conclusion

In this lesson, we have learned how to count all elements or values in an array in PHP. So to count the number of elements within the array, PHP offers two in-built functions. These functions are count() and sizeof(). Both the functions are used to count the number of elements within the array.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.