Problem:
You have an array which has unknown number of elements. You’re looking for a way to know the total number of elements of that array.
Solution:
You can use one of the following two ways to find out the number of elements of an array.
Method 1: Using count() function
The php built-in function count() let you know the number of elements containing in an array. See the example below-
<?php $languages = array("c", "c++", "java", "php", "python", "sql", "mysql", "asp.net", "ruby", "javascript", "ajax", "html", "html5"); echo “Total number of elements is ” . count($languages); ?>
[wpdm_file id=38]
Output:
Total number of elements is 13
Method 2: Using sizeof() function
sizeof() function works similar to the count() function. It can also let you know the number of elements containing in an array. Look at the example-
<?php $languages = array("c", "c++", "java", "php", "python", "sql", "mysql", "asp.net", "ruby", "javascript", "ajax", "html", "html5"); echo “Total number of elements is ” . sizeof($languages); ?>
[wpdm_file id=39]
Output:
Total number of elements is 13
Caution: Empty element is also considered as an element.
The size of the following array shows 3. It counts the empty element inside the array.
<?php $languages = array("c", "c++", ""); echo "Total number of elements is " . count($languages); ?>
[wpdm_file id=41]
Output:
Total number of elements is 3
If you don’t want to consider the empty elements, remove the empty elements from the array using array_filter() function, and, then count the array size, like the following example-
<?php $languages = array("c", "c++", ""); echo "Total number of elements is " . count(array_filter($languages)); ?>
[wpdm_file id=40]
Output:
Total number of elements is 2