PHP: Count all elements in an array
The count() function is used to count the elements of an array or the properties of an object.
Bạn đang xem: Php : count() function
Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
Version:
(PHP 4 & above)
Syntax:
count(array_name, mode) Parameters:
array_name | Specifies the arrayor object khổng lồ count. | Required | Array |
mode | Sets the mode of the function.Possible values :COUNT_RECURSIVE (or 1) : here the count() function counts the array recursively. This is useful for counting all the elements of a multidimensional array. The default value is 0. | Optional | Integer |
Return value:
The number of elements in array_name.
Value Type: Array.
Xem thêm: Bệnh Phụ Nữ Kéo Dài Bao Lâu ? Kinh Nguyệt Lần Đầu Kéo Dài Bao Lâu
Note: The count() function may return 0 for a variable which is not set, but it may also return 0 for a variable that has been initialized with an empty array.The isset() function should be used to kiểm tra whether a variable is set or not.
Example :
Output:
4Pictorial Presentation:

View the example in the browser
Practice here online :
See also
PHP Function Reference
Previous: compactNext: current
PHP: Tips of the Day
User-defined global variables: The scope outside of any function or class is the global scope. When a PHP script includes another (using includeor require) the scope remains the same. If a script is included outside of any function or class, it"s global variablesare included in the same global scope, but if a script is included from within a function, the variables in the includedscript are in the scope of the function.
Within the scope of a function or class method, the global keyword may be used khổng lồ create an access user-defined global variables.
Example:
Output:
0First log message!1Second log message!2A second way lớn access variables from the global scope is lớn use the special PHP-defined $GLOBALS array.
This means that the log_message() function could be rewritten as:
function log_message($message) // Access the global $amount_of_log_calls variable via the // $GLOBALS array. No need for "global $GLOBALS;", since it // is a superglobal variable. $GLOBALS<"amount_of_log_calls"> += 1; echo $messsage;One might ask, why use the $GLOBALS array when the global từ khóa can also be used lớn get a global variable"s value? The main reason is using the global từ khoá will bring the variable into scope. You then can"t reuse the same variable name in the local scope.