Count Array PHP Example | How to use PHP Count() Function
Summary: In this article, you will learn Count Array PHP with Example, and also learn How to Count Array Elements in PHP, Let’s understand Array Count in details. I Hope you will enjoy it!
Count Array PHP Overview
- The PHP count() function is used to Count Array Elements in PHP, or also you can say that the count() function is used to get get the number of elements or values in an array. this function returns the number of items in the array.
- PHP array count() method is basically used to count the items of an array or the properties of an object.
- if the function returns 0 for a variable that has been initialized with an empty array. furthermore, if the array is not initialized, then you will see an error. In that case, you can use the PHP isset() function to check whether a variable is set or not.
- For an object, if you have installed SPL, then you can hook into count() by implementing the interface Countable. The interface has only one method, Countable::count(), which returns a return value for the count() function.
Important Note: You can use the count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array. If the array isn’t initialized, then display an error. In that case, you can use the isset() function to check whether a variable is set or not.
Using PHP count() Function Example:
Example:1
1 2 3 4 |
<?php $brands = ['Van Heusen', 'Gucci', 'Arrow', 'John Players', 'Louis Phillipe', 'Wills Lifestyle']; echo count($brands); ?> |
It will print array size : 6
Example:2
1 2 3 4 |
<?php $veg = ['Beet', 'Radish', 'Potato', 'Sweet Potato', 'Garlic']; echo count($veg); ?> |
It will print array size : 5
Using PHP sizeof() Function Example
Example:1
1 2 3 4 |
<?php $brands = ['Van Heusen', 'Gucci', 'Arrow', 'John Players', 'Louis Phillipe', 'Wills Lifestyle']; echo sizeof($brands); ?> |
It will print array size : 6
Example:2
1 2 3 4 |
<?php $veg = ['Beet', 'Radish', 'Potato', 'Sweet Potato', 'Garlic']; echo sizeof($veg); ?> |
It will print array size : 5
Explanation: as per example out, you can see that when you will used count() or sizeof() function, they will provide the same result. both functions work the same, we can say that both functions are identical.
Conclusion:
In this article, you have learned How to Count Array Elements. I hope you will enjoy it!. if have any query related program then contact me at info@tutorialscan.com I will try to resolve the problem. Stay healthy, stay safe! Happy coding! enjoy it!