PHP source code reading: count function-php Tutorial

Source: Internet
Author: User
PHP source code reading: in PHP programming, when traversing an array, the count function often needs to calculate the length of the array as the condition for judging the end of the loop, in PHP, array operations are very frequent, so count is also a common function. The following describes the specific implementation of the count function.

I have a more detailed description of the PHP source code on github. If you are interested, you can look around and give a star. PHP5.4 source code annotation. You can use the commit record to view the added annotations.


int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

The count function calculates the number of all elements in an array or object.

For objects, if you have installed the SPL extension, you can call the count function by implementing the Countable interface. The Countable interface has only one Countable: count () method. this method returns the return value of the count () function.

Parameter description


If the mode parameter is set to COUNT_RECURSIVE (or 1), count () recursively calculates the array. It is particularly useful when calculating multi-dimensional arrays.

If the first parameter is not an array or an object implementing the Countable interface, the count function returns 1.

Note: The count function can detect recursion to avoid infinite loops, but returns the E_WARNING prompt when there is infinite recursion or a greater value than the expected value.

Running example Common Application

$arr1 = array(1, 2, 3, 4, 5);$val1 = count($arr1); // 5

Multi-dimensional array

$arr2 = array('apple', 'banana', array('cat', 'camel'), 'dog');$val2_1 = count($arr2); // 4$val2_2 = count($arr2, 1); // 6

Numbers and strings

$str = "hello world";$int_val = 1;$val3 = count($str); // 1$val4 = count($int_val); // 1

Common Object

class User {    private $name;    private $address;}$user = new User();$val5 = count($user); // 1$val6 = count((array) $user); // 2

Array-like object

class User extends ArrayObject {    private $name;    public function __construct() {        $this->name = 'hhq';    }    public function getName() {        return $this->name;    }    public function count() {        return 2;    }}$user2 = new User();$val7 = count($user2); // 2

Implement Countable interface object

class User implements Countable {    public function count() {        return 3;    }}$user3 = new User();$val8 = count($user3); // 3 


Enter the switch statement detection parameter type

If it is NULL, 0 is returned directly.

If it is an array, call the php_count_recursive function to select the number of array elements

If it is an object, first check whether it is an array object (array-like object). If yes, calculate the number of array objects.

Otherwise, if the object implements the Countable interface, the Countable count method is called.

Finally, 1 is returned for all other types, such as integer arrays or strings.

Source code explanation

For a normal array, the count function calls the php_count_recursive function to perform the following operations:

If the number of recursive accesses to the current hash Bucket exceeds 1, it indicates repeated recursion and an E_WARNING error is returned.

Otherwise, the number of array elements of the current array layers is calculated.

If Recursive parameter options are available, recursive access continues.

If the parameter is of the object type, the system first determines whether the handler is defined. Handler is the object structure in the PHP kernel, which containsCount_elementsField is actually a function. If an object performs the same way as an arrayArray-like objectThen the count_elements function is executed. The specific implementation is that the class inherits PHP's ArrayObject and implements the count function in the class. the specific call is the count function. if the class does not implement the count function, count returns 0, otherwise, the return value of the count function of the object is returned.

If it is another data type 1, string

2. numbers

3. if both the if values in the object branch are false, the system does not inherit the ArrayObject and does not implement the Countable interface.

1 is returned for all these types.

Note that if you need to calculate the number of attributes of an object, you can first convert the object into an array and then call the count function. For example: $ count_value = count (array) $ user );


When reading the source code of the count function, one step gets stuck, that is, the if (Z_OBJ_HT_P (array)-> count_elements) step, because it is impossible to write a demo into this branch, I searched for a lot of information on the Internet, so I consulted TIPI's reeze and finally got the desired answer. Ask if you don't understand. haha.

The original article is limited in writing, so it is easy to learn. if there is anything wrong with the article, please let us know.

I can write more excellent articles. thank you!


I can write more excellent articles. thank you!

Any payment method

About the Author: hoohack

An ongoing Cainiao personal homepage · My Articles · 15 ·

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.