Access characters in a string using array syntax

Suppose we have this code $test = 'text'; . What is the difference between echo $test[0] and echo $test{0} ? The result is the same.

Is it good to handle a variable containing a string similar to an array of characters?

+8
source share
3 answers

Ok, I will collect my comments as an answer:

Quote manual

You can also use curly braces to access strings, as in $ str {42}, for the same purpose. However, this syntax has been deprecated since PHP 7. Use square brackets instead.

Also, although undocumented, the {} accessor also works for arrays, which makes $ foo {$ bar} and $ foo [$ bar] completely equivalent. This is just the old syntax for the convenience of Perl programmers.

As for your second question, if it is good practice to treat strings as an array of characters: Yes, if that is useful for your task, do it. In low-level languages ​​such as C, strings are arrays of characters, so it's natural to treat them like this.

BUT keep in mind that PHP has poor Unicode support. Therefore, if your string is in multibyte encoding (i.e. UTF-8), this may not work as expected. In this case, it is better to use multibyte functions .

+14
source

You can write "Hello, I am a string character $ string {0}"

But you can not write "Hello, I am a character string $ string [0]"

You should use the string concatenation character, for example, "Hello, I am character string". $ String [0];

+1
source

{0} is the abbreviation for the first character of this string (since php is based on a zero value) - so $test{0} will return t

[0] will get the first record in the array (again, since php is based on a zero value).

The odd thing here is that php treats the string as an array of characters, so the first character text is the same as:

 $test = array('t', 'e', 's', 't'); echo $test[0]; // t 
-one
source

All Articles