2

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.

4
  • Why can't you do it that way? Commented Nov 12, 2013 at 11:13
  • The second way is the correct one. Commented Nov 12, 2013 at 11:16
  • I don't understand the problem. The first example you give works since PHP 5.4.0, the second example will work in every version. Commented Nov 12, 2013 at 11:17
  • 1
    @betadevil problem is that in debugger you can only evaluate expressions but not execute any code. So OP wants to get value as an expression, i.e. one-liner Commented Nov 12, 2013 at 11:21

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.