14
In the PHP manual, we can see New Features the functionality of Array and String literal Dereferencing.
Example:
echo 'string'[2]; // r
echo ['stack', 'overflow'][1]; //overflow
Thinking in case you get one index of a string or array, would already work in other versions of PHP, as long as the Array or string is in a variable.
$var = 'string';
echo $var[2]; // 'r'
In PHP 5.4, I know we now have direct access to members of a array which are returned by a function, and which is very useful by the way (Function array Dereferencing).
But in the case of PHP 5.5, I don’t understand what the purpose of getting a value, through an index, directly from a string or a array, since these are not assigned to a variable?
For me, it would make no sense for the programmer to make use of the first example above.
Is there a more robust purpose than the first example?
Good your answer. After your example, I imagined a usability with strings, which could be:
$string = '/Minha string/';
echo trim($string, '/')[0]; //M
– Wallace Maxters
One question to clarify is that when I say "it is not assigned to the variable", I mean the fact that we programmers have to manipulate strings and arrays usually from external sources (such as DB, a file or $_POST), and that requires them to be in variables (or in some return of a method or function). Hardly anyone would declare a literal string to get the first letter using this feature, since he already knows what the letter is and it would be easier to write it there. , that’s why I quoted about variables. A "known" string would not need this treatment
– Wallace Maxters
As I said, the use with constant in the index is not very advantageous.
– Maniero
It’s amazing how people find excellent utilities for functions that at first glance are completely useless.. + 1
– RodrigoBorth