Strings as arrays in php

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

$str = 'String'; echo $str[0]; echo $str[1]; //result S t echo count($str) //result 1 

Why can I walk through them, as in an array, but cannot count them with a score? (I know that I can use strlen ())

+8
source share
2 answers

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

+22
source

Because strings are not arrays. They allow you to find offsets in bytes of letters (which are not necessarily letters in a multibyte character string), using the same syntax for your convenience, but not about that.

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

In short: a string is not an array, even if the tiny part of their syntax is similar.

+7
source

All Articles