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
If you just want to return the first item in the array, use the current() function.
return current($foo->getBarArray());
http://php.net/manual/en/function.current.php
Previously in PHP 5.3 you had to do this:
function returnArray() {
return array(1, 2, 3);
}
$tmp = returnArray();
$ssecondElement = $tmp[1];
Result: 2
As of PHP 5.4 it is possible to dereference an array as follows:
function returnArray() {
return array(1, 2, 3);
}
$secondElement = returnArray()[1];
Result: 2
As of PHP 5.5:
You can even get clever:
echo [1, 2, 3][1];
Result: 2
You can also do the same with strings. It's called string dereferencing:
echo 'PHP'[1];
Result: H
PHP can not access array results from a function. Some people call this an issue, some just accept this as how the language is designed. So PHP makes you create unessential variables just to extract the data you need.
So you need to do.
$var = foobar();
print($var[0]);
This is too far-fetched, but if you really NEED it to be in one line:
return index0( $foo->getBarArray() );
/* ... */
function index0( $some_array )
{
return $some_array[0];
}
If it is just aesthetic, then the Object notation will work if you return an object. As far as memory management goes, no temporary copy if made, only a change in reference.
Extremely ghetto, but, it can be done using only PHP. This utilizes a lambda function (which were introduced in PHP 5.3). See and be amazed (and, ahem, terrified):
function foo() {
return array(
'bar' => 'baz',
'foo' => 'bar',
}
// prints 'baz'
echo call_user_func_array(function($a,$k) {
return $a[$k];
}, array(foo(),'bar'));
The lengths we have to go through to do something so beautiful in most other languages.
For the record, I do something similar to what Nolte does. Sorry if I made anyone's eyes bleed.