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

霸气de小男生 提交于 2019-12-01 18:54:17

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]

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);

Explode return an array, not reference.

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

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',',');
$pieces = explode(',','1,2,3', 1);

Use the first index with:

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