Why can't I use an array index on the return value of a function? [closed]

笑着哭i 提交于 2019-12-04 03:36:33

问题


Why can't I do this?

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

Every other language supports it.

Answers I'm looking for: (since people seem to think this is a pointless rant)

Is there some sort of a difference between how a variable and a return value behaves that I should be made aware of?

Was this a design decision? Were they just lazy? Is there something about the way the language was built that makes this exceedingly difficult to implement?


回答1:


Why can't I do this?

Because PHP doesn't currently support this syntax. But you can pass it to a function, e.g.:

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

Otherwise, you have to assign the return value to a variable first, then access via index.

More Info:

So one can chain method calls or property access. Now for a long time people requested the same thing for array offset access. This was often rejected due to uncertainties about memory issues, as we don't like memory leaks. But after proper evaluation Felipe committed the patch which allows you to do things like:

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

So, it is in the development pipeline but, as I stated, is not currently supported.

Update

PHP >= 5.4 now supports function array dereferencing, e.g. foo()[0]




回答2:


In my framework I wrote a function to be able to do it with all possiible array:

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

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



回答3:


Explode return an array, not reference.

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



回答4:


You might also consider....

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

or

  $value_I_want_to_keep=strtok('1,2,3',',');



回答5:


$pieces = explode(',','1,2,3', 1);

Use the first index with:

$pieces[0];


来源:https://stackoverflow.com/questions/6216957/why-cant-i-use-an-array-index-on-the-return-value-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!