Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: get array element

Tags:

arrays

php

Why does this code not work?

echo explode("?", $_SERVER["REQUEST_URI"])[0];

It says syntax error, unexpected '['.

Oddly, this works:

$tmp = explode("?", $_SERVER["REQUEST_URI"]);
echo $tmp[0];

But I really want to avoid to create such a $tmp variable here.

How do I fix it?


After the helpful answers, some remaining questions: Is there any good reason of the design of the language to make this not possible? Or did the PHP implementors just not thought about this? Or was it for some reason difficult to make this possible?

like image 317
Albert Avatar asked Aug 14 '10 19:08

Albert


3 Answers

Unlike Javascript, PHP can't address an array element after a function. You have to split it up into two statements or use array_slice().

like image 157
bcosca Avatar answered Nov 09 '22 06:11

bcosca


This is only allowed in the development branch of PHP (it's a new feature called "array dereferencing"):

echo explode("?", $_SERVER["REQUEST_URI"])[0];

You can do this

list($noQs) = explode("?", $_SERVER["REQUEST_URI"]);

or use array_slice/temp variable, like stillstanding said. You shouldn't use array_shift, as it expects an argument passed by reference.

like image 4
Artefacto Avatar answered Nov 09 '22 05:11

Artefacto


It's a (silly) limitation of the current PHP parser that your first example doesn't work. However, supposedly the next major version of PHP will fix this.

like image 3
J Cooper Avatar answered Nov 09 '22 07:11

J Cooper