Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings as arrays in php

Tags:

arrays

string

php

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() )

like image 963
dofenco Avatar asked Jun 19 '13 14:06

dofenco


2 Answers

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.

like image 77
deceze Avatar answered Oct 20 '22 20:10

deceze


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.

like image 39
GolezTrol Avatar answered Oct 20 '22 19:10

GolezTrol