12

I know that strings in php are ..... strings but for example I can do

$str = 'String';
echo $str[0];
echo $str[1];

//result
S
t

echo count($str)
//result
1

Why I can walk trough them like in an array but can't count them with count? (I know that I can use strlen() )

1
  • 1
    Because indexing into a string with [] is syntactic sugar. Strings are not arrays in PHP. Commented Jun 19, 2013 at 14:17

2 Answers 2

26

Because that's how it works. You can access specific byte offsets using bracket notation. But that doesn't mean the string is an array and that you can use functions which expect arrays on it. $string[int] is syntactic sugar for substr($string, int, 1), nothing more, nothing less.

Sign up to request clarification or add additional context in comments.

8 Comments

I'd rather call them character offsets, but you're right about the sugar.
LOL, well timed comment. Well, they're not character offsets! Try: $s = '漢字'; $s[1];
LOL, good timing indeed. Rather than characters, I should have used code points, but bytes seems to be referring too much to the underlying structure and assumes PHP is not and never will be UTF16 or any other multi byte character set. I must admit I'm not sure though, and I can't find what the docs have to say about it.
Byte offset is exactly what it is; it's not code point or character. See What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text. And whatever PHP does in the future is entirely open to speculation; there's nothing like character-based strings coming in the foreseeable future as far as I know.
The notion that accessing the bytes (not characters) of a string in PHP is merely syntatic sugar is wrong, since you can assign (change) bytes within a string using an index, but not make such changes with substr. Using indexing, PHP allows you to treat strings are arbitrary blocks of memory, needed to process a variety of non-text data sources.
|
8

Because strings are not arrays. They allow you to find letters byte offsets (which aren't necessarily letters in a multi-byte character string) using the same syntax for your convenience, but that's about it.

Arrays can have keys as well and can be sorted. If strings were full arrays, you could give each letter a key, or sort the letters alphabetically using one of the array functions.

Long story short: a string is not an array, even when a tiny part of their syntax is similar.

1 Comment

I think it important to distinguish between "letters" and byte offsets. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.