12

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

Is it a good practice to treat a variable which contains a string like a array of character?

5
  • 1
    "What's the diferece betwen echo $test[0] and echo $test{0}? The result is the same." In conclusion, by the definition of difference, there is no difference. Commented Jan 19, 2013 at 22:13
  • If there is no diference. Why i should use $foo[n] or $foo{n}? What's the better one? Commented Jan 19, 2013 at 22:19
  • 2
    To quote the manual: "Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 6. Use square brackets instead." Commented Jan 19, 2013 at 23:44
  • Possible duplicate of stackoverflow.com/questions/335205/php-string0-vs-string0?rq=1 Commented Jan 19, 2013 at 23:45
  • @fab Why don't you post your comment as an answer? It is the right and full answer to the question. Commented Jan 20, 2013 at 2:51

3 Answers 3

22

Okay, I'll aggregate my comments as an answer:

To quote the manual

Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 7 . Use square brackets instead.

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

Concerning your second question, if it is good practice to treat strings like an array of characters: Yes, if it is useful for your task, do it. In low level languages like C, strings are arrays of characters, so it is quite natural to treat them like that.

BUT keep in mind that PHP has bad unicode support. So if your string is in multi-byte encoding (ie UTF-8), this might not work as expected. Better use the multibyte functions in that case.

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

Comments

2

https://www.php.net/manual/en/language.types.string.php

Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

So, always use square brackets $str[0].

Comments

1

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

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

You have to use string concatenation sign like
"Hello, I am a character of a string " . $string[0];

2 Comments

Adding to this, "Hello, I am a character of a string {$string[0]}" ("complex string syntax" is what it's called) is fine too.
You don't need to use string concatenation. You can just use braces, like @Hissvard said.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.