any idea how if the following is possible in PHP as a single line ?:
... It doesn
I am guessing that this is a built-in or library function, since it sounds like you cannot edit it directly. I recommend creating a wrapper function to give you the output you need:
function functionThatReturnsOneElement( $arg )
{
$result = functionThatReturnsAnArray( $arg );
return $result[0];
}
$firstElement = functionThatReturnsOneElement();
You can do this in one line! Use array_shift().
<?php
echo array_shift(i_return_an_array());
function i_return_an_array() {
return array('foo', 'bar', 'baz');
}
When this is executed, it will echo "foo
".
Unfortunately, that is not possible with PHP. You have to use two lines to do it.
list() is useful here. With any but the first array element, you'll need to pad it with useless variables. For example:
list( $firstElement ) = functionThatReturnsAnArray();
list( $firstElement , $secondElement ) = functionThatReturnsAnArray();
And so on.
If it's always the first element, you should probably think about having the function return just the first item in the array. If that is the most common case, you could use a little bit of coolness:
function func($first = false) {
...
if $first return $array[0];
else return $array;
}
$array = func();
$item = func(true);
My php is slightly rusty, but i'm pretty sure that works.
You can also look at array_shift() and array_pop().
This is probably also possible:
array(func())[0][i];
The 0 is for the function.
$firstItem = current(returnsArray());