-1

Is there any alternative to operator[] for arrays in php?

function getArray() {
    return array(1, 2, 3);
}
$e = getArray()[1];

In my php version this doesn't work. Any suggestons of graceful syntax?

At the moment the two-line solution seems to be the only possibility:

$arr = getArray();
$e = arr[1];

Thanks

VladRia
  • 1,475
  • 3
  • 20
  • 32

2 Answers2

2

Just change it to be a two-liner:

function getArray() {
    return array(1, 2, 3);
}
$e = getArray();
echo $e[1];
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

You can access it like this:

function getArray() {
    return array(1, 2, 3);
}

$e = getArray();
echo $e[1];

It will have a consistent behavior across all PHP versions.

Gab
  • 5,604
  • 6
  • 36
  • 52
Daan
  • 12,099
  • 6
  • 34
  • 51