PHP count() Function | How to count all elements or values in an array

Summary: in this article, you will learn PHP count() function and How to count all elements or values in an array? let’s understand in details about PHP Count.

Definition and Usage

The count() function in PHP is used to count all elements in an array or the properties of an object and its returns the number of elements in an array.

.
Important Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. furthermore, the interface has exactly one method, Countable::count(), which returns the return value for the count() function.

Version:

(PHP 4 and above)

Syntax:

count(array_name, mode)

Parameter Values

This function accepts two parameters out of which one is mandatory while the other one is optional. Parameters are described below:

Name Description Type
array_name It is a mandatory parameter. Specifies the array or object to count. Array
mode It is a optional parameter. Sets the mode of the function.
Possible values:

  • COUNT_RECURSIVE (or 1): here the count() function counts the array recursively. it is very useful to counting all the elements of a multidimensional array.
  • The default value is 0.
Integer

Return value: The number of elements in array_name.
Value Type: Array.

.
Important Note: The PHP count() function may return 0 for a variable that is not set, but it may also return 0 for a variable that has been initialized with an empty array.
The PHP isset() function should be used to test whether a variable is set or not.

Technical Details

Return Value: Returns the number of elements in the array_name
PHP Changelog: The mode parameter was added in the PHP 4.0+ or PHP 4.2
PHP Version: 4.0+

PHP count() Function Example:

Example:1

4

Example:2

Normal count: 4
Recursive count: 11

Example:3

7

PHP Count() Function Related Question and Answer

Question 1. How to count all elements or values in an array?

Answer: Use the PHP sizeof() or count() function.
To count all elements or values in an array in PHP using the count() or sizeof() function. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that is not set.

Question 2. How do I count characters in a string in PHP?

Answer: The PHP strlen() is a built-in function that returns the length of a given string. furthermore, It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces & special characters.

Conclusion:

In this article, you have learned the count() function and How to count all elements or values in an array in PHP. I hope you will enjoy it!. if have any query then contact on info@tutorialscan.com I will try to resolve the problem.