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.
Version:
(PHP 4 and above)
Syntax:
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:
|
Integer |
Return value: The number of elements in array_name.
Value Type: 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
1 2 3 4 |
<?php $shirts=array("Peter England","Louis","John Players", "Park Avenue"); echo count($shirts); ?> |
Example:2
1 2 3 4 5 6 7 8 9 10 11 |
<?php $LED=array ( "Realme Smart TV"=>array("40 inch", "43 inch"), "Samsung"=>array("43Y1 43 inch", "43Y1 38 inch"), "Xiaomi Mi TV"=>array("32 inch", "36 inch"), "Thomson"=>array("32PATH0011BL 32 inch") ); echo "Normal count: " . count($LED)."<br>"; echo "Recursive count: " . count($LED,1); ?> |
Recursive count: 11
Example:3
1 2 3 4 5 6 7 8 9 10 11 |
<?php $a[0] = 'Sunday'; $a[1] = 'Monday'; $a[2] = 'Tuesday'; $a[3] = 'Wednesday'; $a[4] = 'Thursday'; $a[5] = 'Friday'; $a[6] = 'Saturday'; $result = count($a); echo $result; ?> |
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.