您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php count函数

2024/3/1 20:00:17发布35次查看
最近被问到一个 函数 count 1、count(123456) 对应的输出是什么? 2、count(null) 对应的输出是什么? 以前没有认真的考虑,只是心里有一个印象那就是count() 函数 是计算php数组的个数的。后来下来仔细看了看手册,原来发现: 1、count 函数 是统计数组
最近被问到一个函数count
1、count(123456) 对应的输出是什么?
2、count(null) 对应的输出是什么?
以前没有认真的考虑,只是心里有一个印象那就是count()函数是计算php数组的个数的。后来下来仔细看了看手册,原来发现:
1、count函数是统计数组里所有元素的个数或者对象的属性的个数的,函数原型如下:
    int count(mixed $var[, $mode=count_normal);
    对于对象,如果安装了spl,可以通过countable接口调用count,该接口只有一个countable::count(),此函数返回count的返回值。
2、当设置$mode=1时,会递归对数组进行计算,但是识别不了无限递归。
3、当$var不是array或者object(实现了countalbe::count函数)时:
    count函数将返回1,但当$mixed=null 时,将返回0
count函数实现的源码是:
1 php_function(count) 2 { 3 zval *array; 4 long mode = count_normal; //默认不递归查找元素个数 5 //获取两个参数 6 if (zend_parse_parameters(zend_num_args() tsrmls_cc, z|l, &array, &mode) == failure) { 7 return; 8 } 9 10 switch (z_type_p(array)) {11 case is_null:12 return_long(0);//为空直接返回013 break;14 case is_array: //计算数组元素个数15 return_long (php_count_recursive (array, mode tsrmls_cc));16 break;17 case is_object: {18 #ifdef have_spl19 zval *retval;20 #endif21 /* first, we check if the handler is defined */22 if (z_obj_ht_p(array)->count_elements) {23 retval_long(1);24 if (success == z_obj_ht(*array)->count_elements(array, &z_lval_p(return_value) tsrmls_cc)) {25 return;26 }27 }28 #ifdef have_spl //如果安装了 spl29 /* if not and the object implements countable we call its count() method */30 if (z_obj_ht_p(array)->get_class_entry && instanceof_function(z_objce_p(array), spl_ce_countable tsrmls_cc)) {31 zend_call_method_with_0_params(&array, null, null, count, &retval);32 if (retval) {33 convert_to_long_ex(&retval);34 retval_long(z_lval_p(retval));35 zval_ptr_dtor(&retval);36 }37 return;38 }39 #endif40 }41 default://其他类型返回142 return_long(1);43 break;44 }45 }
以上可以看出,调用count函数时,当$mixed为数组时会调用php_count_recursive 函数
(php_count_recursive,当不是递归获取元素个数时,返回数组的nnumofelements,时间复杂度为n(1),只有mode=1时才会递归计算元素个数);
当$mixed是null时,返回0
默认都是返回1
结论:
    想了解一些php函数的时候还是多看看php手册,以前主要是通过w3c上面了解的。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product