any idea how if the following is possible in PHP as a single line ?:
... It doesn
You can use array_slice()
, like so:
$elementX = array_slice(functionThatReturnsAnArray(), $x, 1);
Also noticed that end()
is not mentioned. It returns the last element of an array.
Sometimes I'll change the function, so it can optionally return an element instead of the entire array:
<?php
function functionThatReturnsAnArray($n = NULL) {
return ($n === NULL ? $myArray : $myArray[$n]);
}
$firstElement = functionThatReturnsAnArray(0);
@Scott Reynen
that's not true. This will work:
list(,,$thirdElement) = $myArray;
I think any of the above would require a comment to explain what you're doing, thus becoming two lines. I find it simpler to do:
$element = functionThatReturnsArray();
$element = $element[0];
This way, you're not using an extra variable and it's obvious what you're doing.
As far as I know this is not possible, I have wanted to do this myself several times.