PHP count Function | Return Count of Array Elements

The count Function in PHP is one of the most used inbuilt functions. It returns the count of elements in an array in PHP. In this article, we will discuss the PHP count Function. Also, we will discuss a few examples to demonstrate its usage.

PHP sizeof Function is an alias of the count function.


integer count($array, $mode = 0);


The PHP count Function expects two parameters. One parameter is mandatory while the other is optional. The description of the parameters is given below:

  • $array: The first parameter is a mandatory array for which you require to count elements. Also, you can pass a multi-dimensional array to it.
  • $mode: The second parameter to the PHP count is the mode. It is an optional parameter with the default value as 0. It can have two possible values:
    • 0 – Default. Does not count all elements of multi-dimensional arrays.
    • 1 – Counts the array recursively (counts all elements of a multi-dimensional array).

Return Value

The count Function returns the count of array elements in the array.

PHP count Function diagram


Let’s discuss a few examples to demonstrate the use of array count Function.

Example 1: Single Dimensional Basic Array

	$testArray = array(1, 3, 5, 7, 9);
	$count = count($testArray);
	/* int(5) */

You can count array elements in an array using the count function.

Example 2: Multi-Dimensional Array

For instance, consider a multi-dimensional array input to array count Function.

	$testArray = array(
		array('Chandler', 18),
		array('Monica', 21),
		array('Ross', 10),
		array('Monica', array(
			'Joey', 20
	$outerCount = count($testArray);
	/* int(4) */

	$totalCount = count($testArray, 1);
	/* int(14) */

You can observe the following things:

  • When the mode is 0 (default), the function returns 4 as the total count. This is because it does not count all the array elements recursively.
  • When the mode 1, the function returns 14 as the total count. This is because it counts all the array elements recursively.

Expert Tip

You might believe that count is a very cheap operation. However, there is still a function call overhead with it. If you want to run through large arrays don’t use PHP count in the loops. Instead, for better performance, copy the output of the Function in a variable and use it in the loop.

	for($i=0;$i<count($some_arr);$i++)  { 
    	// Loop Body 

	// Good approach 
	$arr_length = count($some_arr); 
	for($i=0;$i<$arr_length;$i++) { 
	    // Loop Body 


In conclusion, we discussed the PHP count Function in this article. You can learn about other PHP Array Functions on Concatly. Additionally, you can read more about the count Function on PHP Official Documentation.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *