Development

PHP sizeof() Function: And Count() Function

In this post, we are going to discuss how to calculate the number of elements in a given array using the built-in sizeof() function in PHP.
Captain Salem 2 min read
PHP sizeof() Function: And Count() Function

In PHP, an array is a collection of variables (known as elements) that are stored together under a single variable name. It is a data structure that is used to organize and store data in a specific order. The elements in an array can be of any data type, including numbers, strings, objects, or even other arrays.

In some cases, we may need to determine the number of elements in a given array. This is where the sizeof function comes into play.

PHP sizeof() Function

As mentioned, the sizeof() function allows us to determine the number of elements in an input array. The function syntax is as shown below:

sizeof($array, $mode = COUNT_NORMAL)

Thesizeof() function is an alias of the count() function, and both functions are used to determine the number of elements in an array.

The count() function returns the number of elements in an array, while sizeof() returns the same value as count().

The syntax is very similar as shown:

count($array, $mode = COUNT_NORMAL)

Here, $array is the array whose elements you want to count, and $mode is an optional parameter that specifies the behavior of the function.

The $mode parameter can take two values: COUNT_NORMAL (default) and COUNT_RECURSIVE. If you pass COUNT_RECURSIVE as the second argument, the function will recursively count the elements in all arrays and sub-arrays.

However, because sizeof() is just an alias of count(), the two functions can be used interchangeably, and there is no functional difference between them.

Example 1 - Using the sizeof Function

The following shows how to use the sizeof() function to determine the number of elements of a given array.

$array_name = array(1,2,3,4,5,6,7);
echo sizeof($array_name);

This should return the number of elements in the array as:

7

Example 2 - Using the count Function

In the example below, we demonstrate how to use the count() function to determine the number of elements in the array.

$array_name = array(1,2,3,4,5,6,7);
echo sizeof($array_name);

Output:

7

Conclusion

In this tutorial, you learned how to use the sizeof() and the count() functions in PHP to determine the number of elements in an input array.

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.