TheDeveloperBlog.com

Home | Contact Us

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?

PHP vs Node.js with examples, php file, php session, php date, php array, php form, functions, time, xml, ajax, php mysql, regex, string, oop, chop(), bin2hex(), addslashes(), addcslashes() etc.

<< Back to HOW

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





Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf