C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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() <?php $ele = array("Ryan", "Ahana", "Ritvik", "Amaya"); $no_of_ele = count($ele); echo "Number of elements present in the array: ".$no_of_ele; ?> Output Number of elements present in the array: 4 Example 2 <?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 Number of elements present in the array: 8 Example 3: Counting using sizeof() <?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 Number of elements present in the array: 6 Example 4 <?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 Number of elements present in the array: 7 Example 5: Example using 2D array <?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 8 8
Next TopicHow to create newline in PHP
|