2

Why do I have to load a PHP array into a variable before I access its elements?

Why can't I access the elements directly from the result of a function call?

e.g. This works:

$foo = "This is a variable I'm going to split/explode";
$bar = explode(' ', $foo);
echo $bar[1];

But this doesn't:

$foo = "This is a variable I'm going to split/explode";
echo explode(' ', $foo)[1];
1
  • It does work from PHP 5.4 and above. Commented Jul 9, 2013 at 13:32

1 Answer 1

7

Because array dereferencing only became available in PHP 5.4. If you want to do that you'll need to upgrade to at least that version.

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

2 Comments

They just didn't have that feature. New versions introduce new functionality. PHP 5.4 introduced array dereferencing. The ones before it did not.
Thanks - Looks like I have version 5.3.3 - found by inserting phpinfo() in my code. Looks like it wasn't implemented before because they were worried about memory leaks - schlueters.de/blog/archives/…

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.