function returnsAnArray ()
{
return array ('test');
}
echo returnsAnArray ()[0];
generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable?
Here's one way, using the list language construct
function returnsAnArray ()
{
return array ('test');
}
list($foo)=returnsAnArray();
You could grab a sequence of elements from an offset by combining this with array_slice
list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3);
Define a new function for returning a specific index from an array.
function arr_index($arr, $i) { return $arr[$i]; }
You might want to add some error and type checking there.
And then use it like this:
echo arr_index(returnsAnArray(), 0);
Happy Coding :)
This will work if there is only one member in the array:
<?php
echo current(returnsAnArray());
?>
Another option:
<?php
echo reset(functionThatReturnsAnArray());
?>
Similar thread: PHP: Can I reference a single member of an array that is returned by a function?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With