Access Array Returned by a Function in PHP

Access array returned by a function in php

Since PHP 5.4 it's possible to do exactly that:

getSomeArray()[2]

Reference: https://secure.php.net/manual/en/language.types.array.php#example-62

On PHP 5.3 or earlier, you'll need to use a temporary variable.

Getting element from PHP array returned by function

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);

Access array returned by function in php

You miss return value assignment:

$array = queryKeys($values);
echo $array['value_es'];

Access array element that's returned from a function right from the function call

That's possible with PHP 5.4, quoting:

As of PHP 5.4 it is possible to array dereference the result of a
function or method call directly. Before it was only possible using a
temporary variable.

Example from php.net:

function getArray() {
return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

More Info:

  • http://php.net/manual/en/language.types.array.php

PHP: Access Array Value on the Fly

I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

$variable = array('a','b','c');
echo $variable[$key];
unset($variable);

Or, you could write a small function:

function indexonce(&$ar, $index) {
return $ar[$index];
}

and call this with:

$something = indexonce(array('a', 'b', 'c'), 2);

The array should be destroyed automatically now.



Related Topics



Leave a reply



Submit