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
However I was expecting, two type of output-
If it is an array, php might convert it into string so the array will become-
'texben'
so it may output - 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)
But every time it output- 5
My consideration from the output is 5
from array
word count but I am not sure. If it is the case how PHP is doing this ?(means counting 5)
The function casts the input as a string, and so arrays become Array
, which is why you get a count of 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. However in PHP 5.3 and above, strlen()
will return NULL
for arrays.
From the Manual :
strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.
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.
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.
You can easily verify this, by running this code:
$a = array('tex','ben');
echo $a;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.