PHP - why doesn't count() work like strlen() on a string?
A string is an array开发者_Python百科 of characters, correct? If so, then why does count()
not produce the same result as 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.
How exactly a string is being handled internally by a specific programming language, must not necessarily mean you can handle it equally to therefore "related" data types. What you describe may be possible in plain C. However PHP is not C and so is not following the same characteristics.
Strings are just a series of charactes, and count
only counts number of elements in an array.
using $string[$index]; its just a shortcut kinda of thing to help you find Nth character,
you could use count(explode('',$string));
which presumably is what strlen
does
so lesson for today is
count == array length
strlen == string length
count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs:
http://php.net/manual/en/function.strlen.php
count is more preferabaly user for array value count strlen its count only the no of char in str.....
精彩评论