0

I sometimes get values from an array like this: $var = array ('key1' => 'value1')['key1']; , so $var should be equal to value1

I run code like this in a server having PHP v5.4.16 , for example, explode ('-', $str)[0]; and it works fine. Now if I transfer this code to another server which uses PHP v5.3.10 I get an error (syntax error): syntax error, unexpected '[' ...

Is this because of the version? (I don't think so because the difference between versions is so small..), or some setting in the server? Can anyone enlighten me?

5
  • 3
    PHP 5.4 adds the short array syntax. Commented Feb 5, 2014 at 13:18
  • So it's all about the version? Ok thank you (Y) Commented Feb 5, 2014 at 13:21
  • 2
    It has nothing to do with short array syntax but with array dereferencing. Commented Feb 5, 2014 at 13:21
  • 1
    @MichalBrašna That's right. "Function array dereferencing has been added, e.g. foo()[0]". See php.net/manual/en/migration54.new-features.php Commented Feb 5, 2014 at 13:22
  • I found this according to @MichalBrašna php.net/manual/en/language.types.array.php#example-89 Commented Feb 5, 2014 at 13:24

1 Answer 1

1

Yes, it depends on the version of PHP you are running. As PHP docs mentions

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.

In PHP 5.3 you would have to use

$exploded = explode('-', $str);
$first = $exploded[0];
// or
list($first,) = explode('-', $str);

In PHP 5.4 and later you can use

$first = explode('-', $str)[0];
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.