strlen on array returns 5 in php

Trialcoder picture Trialcoder · Jul 1, 2013 · Viewed 7.3k times · Source

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-

  1. If it is an array, php might convert it into string so the array will become-

    'texben' so it may output - 6

  2. 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)

Answer

MrCode picture MrCode · Jul 1, 2013

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.