1

I was questioning myself, why does this work?

$key = 'question_1';
$key = explode('_', $key)[1];
var_dump($key); 

Result: string(1) "1"

A collegue of mine used this, but how is this called?

5
  • 1
    We don't know why you haven't seen this before, but it's widely used across many languages and is called array dereferencing. PHP has gotten it pretty late actually. Commented Jul 24, 2014 at 9:46
  • 2
    It's called array dereferencing. You didn't see it before because many systems run < 5.4 and so don't have this feature Commented Jul 24, 2014 at 9:46
  • 2
    Valid syntax in 5.4+. You won't have seen it before if you've been stuck with 5.3. Commented Jul 24, 2014 at 9:46
  • @scragar I'd hardly call it "preferred". If you have to use list(), you may as well just assign to a variable and use $var[1] on the next line. E.g. list doesn't help with something like foo(explode(...)[1]). Commented Jul 24, 2014 at 9:50
  • Thank you all! I think it's a very nice way of getting values from an array. Commented Jul 24, 2014 at 11:14

2 Answers 2

7

It's called array dereferencing, you can read about it here:

Function array dereferencing has been added, e.g. foo()[0].

Another bit of information here:

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.

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

Comments

2

Why does it work? Because you are using PHP/5.4 or greater: Function array dereferencing. In earlier versions, you had to store the result in a variable before being able to access individual bits:

$key = 'question_1';
$key = explode('_', $key);
$key = $key[1];
var_dump($key);

Though, for this particular case, good old list() (available since PHP/4) is just as fancy:

$key = 'question_1';
list(,$key) = explode('_', $key);
var_dump($key);

On this line, PHP/5.5 adds a new variant: array and string literal dereferencing. It's the same, except that for array/string literals (rather than function calls).

3 Comments

That's not literal dereferencing.
Yeah, sorry, I'll fix it ASAP.
Well, I'm not going to leave a wrong answer intentionally :)

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.