2

Is it possible in PHP to reference an array index on creation of the array?

For example, I need to create a list that will only be used once, in this case to map a word to an index. I know this can be done in Perl, and I think Javascript but can't get it to work in PHP.

$fruit = 2;
$fruitName = ( array( "Apple", "Pear", "Banana", "Kiwi"))[$fruit];

echo $fruitName;

This should output Banana, is this possible or do I have to create the array first?

I realise that I'm just being lazy trying to shortcut it, and I also realise that this post is 7 lines so could have done this 7 times already in the time it took to ask lol

2
  • just remove the () this should be $fruitName = array( "Apple", "Pear", "Banana", "Kiwi")[$fruit]; Commented Jan 6, 2015 at 1:51
  • Thanks RxV seems my PHP version is the issue. I think I did that cos in Perl you'd do @(list)[index], just tried it that way. Commented Jan 6, 2015 at 2:00

1 Answer 1

3

You just have to delete () and then it should work (PHP > 5.4 , see: http://3v4l.org/YpThG)

$fruit = 2;
$fruitName = array( "Apple", "Pear", "Banana", "Kiwi")[$fruit];

echo $fruitName;

Output:

Banana

Also for more information about array dereferencing see: http://php.net/manual/en/language.types.array.php

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

3 Comments

Ah thanks! I'm running 5.3 so that's why. Current stable is 5.6, do you know if that's fully compatible? Don't want to break my app for the sake of a 1 liner.
@Dabrowski On 5.3 it doesn't work you would have to first assign it to a variable. If you have 5.6 then it's no problem!
Yep, I get that, I can upgrade to 5.6 no problem just wanted to check if it's fully backwards compatible but I can always switch it back. Thanks again.

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.