Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting element from PHP array returned by function

Tags:

php

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?

like image 679
Yevgeny Simkin Avatar asked Jan 17 '12 01:01

Yevgeny Simkin


People also ask

Can an array be returned from a function in PHP?

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.

How do you return an array element from a function?

There are three right ways of returning an array to a function: Using dynamically allocated array. Using static array. Using structure.

Which function returns the value of an array in PHP?

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.

What is Array_keys () used for in PHP?

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.


2 Answers

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);
like image 128
Jon Avatar answered Oct 20 '22 17:10

Jon


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
like image 29
anonym Avatar answered Oct 20 '22 15:10

anonym