Background
In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring a new variable to hold the function result.
In PHP, however, this does not appear to be so simple:
example1 (function result is an array)
<?php
function foobar(){
return preg_split('/\s+/', 'zero one two three four five');
}
// can php say "zero"?
/// print( foobar()[0] ); /// <-- nope
/// print( &foobar()[0] ); /// <-- nope
/// print( &foobar()->[0] ); /// <-- nope
/// print( "${foobar()}[0]" ); /// <-- nope
?>
example2 (function result is an object)
<?php
function zoobar(){
// NOTE: casting (object) Array() has other problems in PHP
// see e.g., http://stackoverflow.com/questions/1869812
$vout = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);
return $vout;
}
// can php say "zero"?
// print zoobar()->0; // <- nope (parse error)
// print zoobar()->{0}; // <- nope
// print zoobar()->{'0'}; // <- nope
// $vtemp = zoobar(); // does using a variable help?
// print $vtemp->{0}; // <- nope
Can anyone suggest how to do this in PHP?
After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.
Looks like this will change starting in PHP 5.4.
Also, this answer was originally for this version of the question:
How to avoid temporary variables in PHP when using an array returned from a function
If you just want to return the first item in the array, use the current() function.
http://php.net/manual/en/function.current.php
You could, of course, return an object instead of an array and access it this way:
But I didn't find a possibility to do this with an array :(
Does this work?
Otherwise, can you post the getBarArray() function? I don't see why that wouldn't work from what you posted so far.
There isn't a way to do that unfortunately, although it is in most other programming languages.
If you really wanted to do a one liner, you could make a function called a() and do something like
But other than that, func()[1] is not supported in PHP.
Write a wrapper function that will accomplish the same. Because of PHP's easy type-casting this can be pretty open-ended: