2

Accessing Characters in a String Using the Table Syntax

 2 years ago
source link: https://www.codesd.com/item/accessing-characters-in-a-string-using-the-table-syntax.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Accessing Characters in a String Using the Table Syntax

advertisements

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?


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 6. 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK