Recently asked a function count
1. What is the corresponding output of count ("123456")?
2. What is the corresponding output of count (null)?
I didn't think about it before, but I had an impression in my mind that the count () function computes the number of PHP arrays. Later came down carefully read the manual, originally found:
1, the Count function is the number of all elements in the statistical array or the number of properties of the object, the function prototype is as follows:
int count (mixed $var [, $mode =count_normal);
For an object, if SPLis installed, count can be called through the countable interface, which has only one countable::count (), which returns the return value of count.
2, when set $mode=1, will be recursive array to calculate, but can not recognize infinite recursion.
3. When $var is not an array or an object (implements the Countalbe::count function):
The count function returns 1, but when $mixed=null, 0 is returned
The source code implemented by the Count function is:
1 php_function (count)2 {3Zval *Array;4 Longmode = Count_normal;//default does not recursively find the number of elements5 //get two parameters6 if(Zend_parse_parameters (Zend_num_args () TSRMLS_CC,"z|l", &array, &mode) = =FAILURE) {7 return;8 } 9 Ten Switch(z_type_p (array)) { One CaseIs_null: AReturn_long (0);//ForNull direct return 0 - Break; - CaseIs_array://calculating the number of array elements the Return_long (php_count_recursive (array, mode TSRMLS_CC)); - Break; - CaseIs_object: { - #ifdef HAVE_SPL +Zval *retval; - #endif + /*First , we check if the handler is defined*/ A if(z_obj_ht_p (array),count_elements) { atRetval_long (1); - if(SUCCESS = = Z_obj_ht (*array)->count_elements (array, &z_lval_p (Return_value) tsrmls_cc)) { - return; - } - } -#ifdef HAVE_SPL//If the SPL is installed in /*If not and the object implements countable we call its count () method*/ - if(z_obj_ht_p (array)->get_class_entry &&instanceof_function (z_objce_p (array), spl_ce_countable tsrmls_cc)) { toZend_call_method_with_0_params (&array, NULL, NULL,"Count", &retval); + if(retval) { -CONVERT_TO_LONG_EX (&retval); the Retval_long (z_lval_p (RETVAL)); *Zval_ptr_dtor (&retval); $ }Panax Notoginseng return; - } the #endif + } A default://Other types return 1 theReturn_long (1); + Break; - } $}
As you can see, when you call the Count function, the php_count_recursive function is called when $mixed is an array
(Php_count_recursive, when it is not recursive to get the number of elements, the nnumofelements of the returned array, the time complexity is n (1), only the mode=1 will be recursive calculation of the number of elements);
When $mixed is null, returns 0
The default is to return 1
Conclusion:
If you want to know some PHP functions or read more PHP manual, before mainly through the above knowledge.
PHP Count function