0

If I have a function that returns an array, how can I access a key from it directly from the function call?

Example:

function foo() {
    return array('a' => 1);
}

foo()['a']; //no good
1
  • 1
    from php 5.4 up this foo()[1] is valid syntax. ide's such as dreamweaver won't recognize it as such though and will throw big red lines. but it definitely is possible Commented Jul 23, 2014 at 19:37

2 Answers 2

1

You can't do it directly like that in versions < 5.4. You need to store the return value of foo() somewhere:

function foo() {
    return array('a' => 1);
}

$bar = foo();

echo $bar['a'];

In PHP 5.4 and up, your code will work. Demo.

Sign up to request clarification or add additional context in comments.

2 Comments

@FélixGagnon-Grenier Thanks for reminding me of the 5.4 part; I recalled a change in there somewhere, but forget when it was. :)
meh, thinking about it, my reaction was quite childish, you deserve this :)
0

You have to assign the function to a variable first - like this:

$bar = foo();
$bar['a'];

You have to actually call a function to get a return value - in this case you are trying to get an array value from something which is not an array.

Note, this is true only for versions of PHP before 5.4.

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.