Why can't I use an array index for the return value of a function?

Why can't I do this?

explode(',','1,2,3', 1)[0]

All other languages ​​are supported.

The answers I'm looking for: (since people seem to think this is a meaningless spelling)

Is there any difference between the way the variable behaves and the return value that I should be aware of?

Was it a design decision? Were they lazy? Is there anything in the way the language was built that makes it extremely difficult to implement?

+5
source share
5 answers

Why can't I do this?

Because PHP does not support this syntax. But you can pass it to functions, for example:

current(explode(',','1,2,3', 1));

, .

:

, . . - , . , :

function foo() {
    return array(1, 2, 3);
}
echo foo()[2]; // prints 3

http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html

, , , , .

Update

PHP >= 5.4 , . foo()[0]

+7

, :

function elem($array,$key) {
  return $array[$key];
}

//> usage 
echo elem($whateverArrayHere,'key');
echo elem(explode(),1);
+2

Explode returns an array, not a link.

$tab = explode (',','1,2,3', 1);
$tab[0] = ','
+1
source

You may also consider ....

  list($value_I_want_to_keep)=explode(',','1,2,3', 1);

or

  $value_I_want_to_keep=strtok('1,2,3',',');
0
source
$pieces = explode(',','1,2,3', 1);

Use the first index with:

$pieces[0];
0
source

All Articles