String to Array in PHP

Another interesting PHP  feature that I didn't realize. String can be accessed by both braces or array. Something I learned from reading my colleague's code. One of the benefit when you worked with people from different coding experiences.

My usual way of converting a string to array is first using str_split, then access individual character as array element. Example as shown.
php > $str = "foobar";
php > print_r(str_split($str));
    [0] => f
    [1] => o
    [2] => o
    [3] => b
    [4] => a
    [5] => r
php > print_r(str_split($str)[0]);

However, the code above is unnecessary if you just want to obtain individual character in a string directly. For examples,

Using curly bracket or braces {}
php > $str = "foobar";
php > print $str{0};

Using bracket []
php > $str = "foobar";
php > print $str[0];

However, this only works for single-byte encoding strings as documented in the #PHP  manual.
"Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1." --, emphasis added

No comments:

Post a Comment