What is the purpose of Array and String Dereferencing implemented in PHP 5.5?

14

In the PHP manual, we can see the New Features functionality of Array and String literal Dereferencing .

Example:

echo 'string'[2]; // r
echo ['stack', 'overflow'][1]; //overflow

Thinking about whether to get a index from a string or array , would already work on other versions of PHP, since Array or the string were in a variable.

$var = 'string';
echo $var[2]; // 'r'

In PHP 5.4, I know that we now have direct access to the members of an array that are returned by a function, and that is very useful per sign ( Function array dereferencing ).

But in the case of PHP 5.5, I do not understand what is the purpose of getting a value through an index directly from a string or an array since they are not allocated to a variable?

For me, it would not make sense for the programmer to use the first example above.

Is there a more robust purpose than the first example?

    
asked by anonymous 03.07.2014 / 18:09

1 answer

15

The documentation example is unfortunate (what novelty, right?). In the way it was put, where everything is constant, there is no advantage at all. The documentation should help to understand the purpose of this, but preferred a bureaucratic approach.

Using

echo ['stack', 'overflow'][$x];

It's "better" (or at least the code gets simpler) to do

switch ($x) {
    case 0: 
        echo 'stack';
        break;
    case 1:
        echo 'overflow';
        break;
}

See working in PHP SandBox . also put on GitHub for future reference .

So it is primarily used for code simplification. Imagine if you have 10, 20, 30 elements in this array , as switch would be long.

And in a way to maintain a pattern. If other operations can be done directly with literals, why not? Operations should be done on top of values and not on top of variables. If by chance a value comes from a variable, a return from a function, an expression or a literal should not make a difference. If this had been conceptualized correctly when the language was created, this form existed since version 1.0. Just PHP itself to make this mess.

    
03.07.2014 / 18:29