PHP Array Count Example | How to Count all elements in an array?

Summary: In this article, you will learn, PHP Array Count function Example and How to Count all elements in an array?. let’s understand this article, in details.

Definition and Usage

count() function in PHP returns the number of items in the array. thus, the array count() method is utilized to count the items of an array or the properties of an object.

For objects, if you have installed SPL, then you can hook into PHP count() by implementing or execution the interface Countable. furthermore, the interface has only one method or technique, Countable::count(), which returns a return value for the PHP count() function.

Syntax:

count (mixed $array_or_countable [, int $mode = COUNT_NORMAL]) : int

Parameter Values

Name Description
array_or_countable An array or Countable object.
mode If the optional parameter mode is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is very most useful for counting all the elements of a multi-dimensional array.
Caution PHP count() can detect recursion to avoid an infinite loop however can emit an E_WARNING every time it does (in case the array contains itself more than once) and it returns a count higher than may be expected.
Return Values

Returns the number of elements in array_or_countable. furthermore, when the parameter is neither an array and nor an object with implemented Countable interface, 1 will be returned. There’s one exception, if array_or_countable is NULL, zero (0) will be returned.

Array Count Example

Example 1: count() example

int 3
int 4
Warning: count(): Parameter must be an array or an object that implements Countable in C
int 0
Warning: count(): Parameter must be an array or an object that implements Countable in C
int 1
Example 2: Recursive count() Example

132
Example 3:

Array ( [Laptop] => 1 [Keyboard] => 4 [Mouse] => 2 [CPU] => 1 [Pendrive] => 1 [Harddrive] => 1 )
Example 4: php count rows in an array

7

Conclusion:

In this article, you have learned Array Count in PHP function and How to Count all elements in an array in PHP with example. I hope you will enjoy it!. if have any query then contact me on info@tutorialscan.com I will try to resolve the problem.
Stay healthy, stay safe! Happy coding! enjoy it!