[英]strlen on array returns 5 in php
From the docs - 来自文档 -
int strlen ( string $string )
it takes string as a parameter, now when I am doing this- 它需要字符串作为参数,现在当我这样做时 -
$a = array('tex','ben');
echo strlen($a);
Output - 5
输出 -
5
However I was expecting, two type of output- 不过我期待的是,有两种输出 -
If it is an array, php might convert it into string so the array will become- 如果是数组,php可能会将其转换为字符串,因此数组将变为 -
'texben'
so it may output - 6
'texben'
所以它可能输出 - 6
If 1st one is not it will convert it something like this - 如果第一个不是它会转换它像这样 -
"array('tex','ben')"
so the expected output should be - 18
(count of all items) "array('tex','ben')"
所以预期的输出应为18
(所有项目的数量)
But every time it output- 5
但每次输出 -
5
My consideration from the output is 5
from array
word count but I am not sure. 我从输出中考虑的是
array
字数为5
,但我不确定。 If it is the case how PHP is doing this ?(means counting 5) 如果PHP是这样做的话?(意味着计数5)
The function casts the input as a string, and so arrays become Array
, which is why you get a count of 5. 该函数将输入转换为字符串,因此数组变为
Array
,这就是为什么你得到5的计数。
It's the same as doing: 它和做的一样:
$a = array('tex','ben');
echo (string)$a; // Array
var_dump((string)$a); // string(5) "Array"
This is the behavior prior to PHP 5.3. 这是PHP 5.3之前的行为。 However in PHP 5.3 and above,
strlen()
will return NULL
for arrays. 但是在PHP 5.3及更高版本中,
strlen()
将为数组返回NULL
。
strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.
strlen()在数组上执行时返回NULL,并发出E_WARNING级别错误。
Prior [to 5.3.0] versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
之前[到5.3.0]版本将数组视为字符串Array,因此返回字符串长度为5并发出E_NOTICE级别错误。
Use 采用
$a = array('tex','ben');
$lengths = array_map('strlen',$a);
to get an array of individual lengths, or 获得一系列单独的长度,或
$a = array('tex','ben');
$totalLength = array_sum(array_map('strlen',$a));
to get the total of all lengths 得到所有长度的总和
The array is implicitly converted to a string. 该数组被隐式转换为字符串。 In PHP this yields the output
Array
, which has 5 letters as strlen()
told you. 在PHP中,这会产生输出
Array
,它有5个字母,如strlen()
告诉你的那样。
You can easily verify this, by running this code: 您可以通过运行以下代码轻松验证:
$a = array('tex','ben');
echo $a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.