开发者

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

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Why can't I do this?

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

Every other language suppor开发者_如何学编程ts 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?


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜