PHP sizeof Function | Return Count of Array Elements

The sizeof Function in PHP returns the count of elements in an array in PHP. Also, it is an alias of the count Function. In this article, we will discuss the PHP sizeof Function. Also, we will discuss a few examples to demonstrate its usage.

Syntax

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

Parameters

The 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 sizeof Functionand¬†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 PHP sizeof Function returns the count of array elements in the array.

PHP sizeof Function Diagram
PHP sizeof Function

Examples

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

Example 1: Single Dimensional Basic Array

<?php
	$testArray = array(1, 3, 5, 7, 9);
	$count = sizeof($testArray);
	var_dump($count);
	/* int(5) */
?>

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

Example 2: Multi-Dimensional Array

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

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

	$totalCount = sizeof($testArray, 1);
	var_dump($totalCount);
	/* 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 sizeof 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 sizeof in the loops. Instead, for better performance, copy the the output of the Function in a variable and use it in the loop.

<?php
	
	for($i=0;$i<sizeof($some_arr);$i++)  { 
    	// Loop Body 
	} 


	// Good approach 
	$arr_length = sizeof($some_arr); 
	for($i=0;$i<$arr_length;$i++) { 
	    // Loop Body 
	}
?>

Conclusion

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

Spread the Knowledge

Leave a Reply

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