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

Question:

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

Example:

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

Thinking about the case of getting an index of a string or array , it would work in other versions of PHP, as long as the 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 it's 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, via an index, directly from a string or an array is , since these aren't assigned to a variable?

For me, it wouldn't make any sense for the programmer to make use of the first example above.

Is there any more robust purpose than the first example?

Answer:

The documentation example is unfortunate (so new, right?). In the way it was placed, where everything is constant, there is no real advantage. The documentation should help understand the purpose of this, but they preferred a bureaucratic approach.

Using

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

is "better" (or at least the code is simplified) than doing

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

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

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

And in a way to maintain a pattern. If other operations can be done directly with literals, why not this one? Operations must be done on values ​​and not on variables. If by chance a value comes from a variable, a return from a function, an expression or a literal shouldn't matter. If this had been conceptualized correctly when the language was created, this form would have existed since version 1.0. Only PHP itself to make this mess.

Scroll to Top