PHP字符串充当数组?

PHP字符串充当数组?,php,Php,PHP字符串作为数组,如下所示 $string='test string'; echo $string[0]; // print t 但是当我使用带有字符串变量的count函数时,它只打印1 echo count($string); // print 1 谁能解释一下原因吗?$string[offset]是唯一一种语法糖,可以让您轻松访问字符串的特定字节。尽管语法与访问数组索引的语法相同,但这并不意味着字符串以任何方式充当数组count是一个作用于数组而不是字符串的函数。当您以数组的形式

PHP字符串作为数组,如下所示

$string='test string'; 
echo $string[0];  // print t
但是当我使用带有字符串变量的
count
函数时,它只打印
1

echo count($string); // print 1

谁能解释一下原因吗?

$string[offset]
是唯一一种语法糖,可以让您轻松访问字符串的特定字节。尽管语法与访问数组索引的语法相同,但这并不意味着字符串以任何方式充当数组
count
是一个作用于数组而不是字符串的函数。

当您以数组的形式访问字符串组件时,运行时会检测您正在执行的操作,并在给定位置拾取字符。这与其他语言一样,也是一种常见的快捷方式

PHP_FUNCTION(count)
{   
        zval *array;
        long mode = COUNT_NORMAL;

        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &array, &mode) == FAILURE) {
                return;
        }   

        switch (Z_TYPE_P(array)) {
                case IS_NULL:
                        RETURN_LONG(0);
                        break;
                case IS_ARRAY:
                        RETURN_LONG (php_count_recursive (array, mode TSRMLS_CC));
                        break;
                case IS_OBJECT: {
#ifdef HAVE_SPL
                        zval *retval;
#endif
                        /* first, we check if the handler is defined */
                        if (Z_OBJ_HT_P(array)->count_elements) {
                                RETVAL_LONG(1);
                                if (SUCCESS == Z_OBJ_HT(*array)->count_elements(array, &Z_LVAL_P(return_value) TSRMLS_CC)) {
                                        return;
                                }   
                        }   
#ifdef HAVE_SPL
                        /* 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)) {
                                zend_call_method_with_0_params(&array, NULL, NULL, "count", &retval);
                                if (retval) {
                                        convert_to_long_ex(&retval);
                                        RETVAL_LONG(Z_LVAL_P(retval));
                                        zval_ptr_dtor(&retval);
                                }   
                                return;
                        }   
#endif
                }   
                default:
                        RETURN_LONG(1);
                        break;
        }   
}   
当您调用“count”时,PHP实际做的是将其转换为一个数组(除非它实现了
countable

var_dump( (array)$string);
有关计数,请参阅文档:


如果您正在寻找替代方案,
strlen
将提供长度(以字节为单位),
mb_strlen
将提供字符数长度(在多字节字符集的情况下不相同)

原因是..让我将您链接到count函数的实际实现:(注意,它包含在逻辑位置:array.c中,因为它实际上是指数组/可数的,而不是字符串)


如您所见,..count函数实际上只对数组、spl可数项和NULL(返回0)实现。其他任何操作都将返回int值:1。

对字符串使用
strlen()
。为什么
count($string)
打印1?
如果参数不是数组或不是实现可数接口的对象,则返回1。
阅读文档: