How to count all elements in an array in PHP?

To count all the elements in an array, PHP offers count() and sizeof() functions. The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.

For example

We will discuss the program implementation for all the array elements using both count() and sizeof() methods.

Example 1: Counting using count()

snippet
<?php
	$ele = array("Ryan", "Ahana", "Ritvik", "Amaya");
	$no_of_ele = count($ele);
	echo "Number of elements present in the array: ".$no_of_ele;
?>

Output

Output
Number of elements present in the array: 4

Example 2

snippet
<?php
	$ele = array(14, 89, 26, 90, 36, 48, 67, 75);
	$no_of_ele = sizeof($ele);
	echo " Number of elements present in the array: ".$no_of_ele;
?>

Output

Output
Number of elements present in the array: 8

Example 3: Counting using sizeof()

snippet
<?php
	$ele = array("Jan", "Feb", "Mar", "Apr", "May", "Jun");
	$no_of_ele = sizeof($ele);
	echo " Number of elements present in the array: ".$no_of_ele;
?>

Output

Output
Number of elements present in the array: 6

Example 4

snippet
<?php
	$ele = array(14, 89, 26, 90, 36, 48, 67);
	$no_of_ele = sizeof($ele);
	echo " Number of elements present in the array: ".$no_of_ele;
?>

Output

Output
Number of elements present in the array: 7

Example 5: Example using 2D array

snippet
<?php
	$snacks = array('drinks' => array('cold coffee', 'traffic jam', 'Espresso',
	'Americano'), 'bevrage' => array('spring rolls', 'nuddles'));
	echo count($snacks, 1);
	echo "</br>";
	echo sizeof($snacks, 1);	
?>

Output

Output
8 8
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents