I'm not sure if this is possible, but I can't figure out how to do it if it is...
I want to get a specific element out of an array that is returned by a function, without first passing it into an array... like this...
$item = getSomeArray()[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
What's the correct syntax for this?
Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.
There are three right ways of returning an array to a function: Using dynamically allocated array. Using static array. Using structure.
The array_values() function returns an array containing all the values of an array. Tip: The returned array will have numeric keys, starting at 0 and increase by 1.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
PHP cannot do this yet, it's a well-known limitation. You have every right to be wondering "are you kidding me?". Sorry.
If you don't mind generating an E_STRICT
warning you can always pull out the first and last elements of an array with reset
and end
respectively -- this means that you can also pull out any element since array_slice
can arrange for the one you want to remain first or last, but that's perhaps taking things too far.
But despair not: the (at this time upcoming) PHP 5.4 release will include exactly this feature (under the name array dereferencing).
Update: I just thought of another technique which would work. There's probably good reason that I 've never used this or seen it used, but technically it does the job.
// To pull out Nth item of array:
list($item) = array_slice(getSomeArray(), N - 1, 1);
PHP 5.4 has added Array Dereferencing, here's the example from PHP's Array documentation:
Example #7 Array dereferencing
function getArray() {
return ['a', 'b', 'c'];
}
// PHP 5.4
$secondElement = getArray()[0]; // output = a
// Previously
$tmp = getArray();
$secondElement = $tmp[0]; // output = a
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