A string is an array of characters, correct? If so, then why does count() not produce the same result as strlen() on a string?
-
19PHP doesn't always make sense like you want it to ;-)Matt Ellen– Matt Ellen2011-06-24 11:40:35 +00:00Commented Jun 24, 2011 at 11:40
-
@Matt Ellen it's the same for any lang, why not learn why there are different functions for different tasks?Raoul– Raoul2011-06-24 11:42:49 +00:00Commented Jun 24, 2011 at 11:42
-
@Raoul: what's the same? That different types have different functions applicable to them? Sure, but in some languages lists/arrays of characters and lists/arrays of anything else can be treated the same.Matt Ellen– Matt Ellen2011-06-24 11:47:47 +00:00Commented Jun 24, 2011 at 11:47
-
1@Matt Ellen for clarification, no language makes sense if people jump to conclusions regarding syntax/features.Raoul– Raoul2011-06-24 12:28:40 +00:00Commented Jun 24, 2011 at 12:28
-
@Matt Ellen exactly, I was agreeing with you.Raoul– Raoul2011-06-24 13:20:46 +00:00Commented Jun 24, 2011 at 13:20
7 Answers
Unless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1
1 Comment
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.
2 Comments
sizeof(std::string) won't give you the lenght. Just use the right tool for the right job.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.
5 Comments
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
Comments
count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs: