PHP - why doesn't count() work like strlen() on a string?

Unless it is an object, count casts its argument to an array, and

  count((array) "example")
= count(array("example"))
= 1

A string is an array of characters in C, C++ and Java. In PHP, it is not. Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the []-selector, but it still dosn't make it an array.


count() counts the number of entries in an Array.

$test = array(1,2,3);
echo count($test);

Output: 3

Why would you want to use count() on a string when strlen() can do that? Are you not sure if your input is a string or an array? Then use is_array() to check that.

Tags:

Php