2

For the life of me, I can't understand this godforsaken language. This:

$x = explode(' ', 'a b c');
echo $x[0];

works just fine. But:

echo explode(' ', 'a b c')[0];

returns an error. What gives?

5
  • 1
    echo current(explode(' ', 'a b c')); Commented Mar 24, 2011 at 10:43
  • 1
    @biakaveron this won't work for [1] :) Commented Mar 24, 2011 at 10:44
  • Yep, but the question is about getting first element :p Commented Mar 24, 2011 at 10:47
  • +1 biakaveron: I have used that little trick before, but not many people know about the current() function Commented Mar 24, 2011 at 10:50
  • @biakaveron, the question is about why it gives an error. Commented Jul 5, 2013 at 19:18

3 Answers 3

4

It is simply a syntax error, you can use the array brackets [] only on variables in PHP.

Example:

echo $x[0];
Sign up to request clarification or add additional context in comments.

Comments

2

That syntax isn't supported by the PHP parser, yet. It is called array dereferencing and has been added in the PHP trunk already.

2 Comments

Funny! So PHP parser and trunk developers are out of sync! PHP Parser team had better move fastly!
Not quite true, I believe it is added to the trunk for the new PHP version which can be 5.4 or 6.
1

You can do that in PHP 5.4... it's time to upgrade.

Per the manual:

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.

As of PHP 5.5 it is possible to array dereference an array literal.

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

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

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

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.