Question

Having an array $a and a key $key, it's usually as simple as $a[$key] to get the value for that key in the array. However, if the array is returned by a function like this:

function getArray(){
    return array('a' => someObjectValue1, 'b' => someObjectValue2);
}
echo getArray()['a'];

, then you can't simply do getArray()[$key] as in some versions of PHP this would give you

Parse error: syntax error, unexpected '[', expecting ',' or ';'

Then ofcourse something like this would work:

$a = getArray();
echo $a['a'];

but I'm in the Watch window of XDebug and I can't do that.

Any ideas? Thanks.

Was it helpful?

Solution

There are different ways to resolve that. For example, one-liner for display desired value may be:

function foo()
{
   return array('bar'=>1, 'baz'=>2);
}

$value = array_shift(array_intersect_key(foo(), array('baz'=>null))); //you want $value

-but this looks weird and may be it have sense to create debug function, like:

function getValueByKey(array $array, $key)
{
   return $array[$key];
}

$value = getValueByKey(foo(), 'baz');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top