PHP: get array element

Why is this code not working?

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

It says syntax error, unexpected '[' .

Oddly enough, this works:

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

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

How to fix it?


After helpful answers, some remaining questions: Is there a good reason to develop a language to make this impossible? Or did the PHP developers just not think about it? Or was it for some reason difficult to make this possible?

+6
arrays php
source share
6 answers

This is a (stupid) limitation of the current PHP parser that your first example does not work. However, presumably, the next major version of PHP will fix this.

+3
source share

Unlike Javascript, PHP cannot address an array element after a function. You must split it into two statements or use array_slice ().

+5
source share

This is only allowed in the PHP development branch (this is a new feature called array dereferencing):

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

You can do it

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

or use the array_slice / temp variable, for example stillstanding . You should not use array_shift as it expects the argument passed by reference.

+4
source share

Take a look at this previous question .

Hoohaah suggesting using strstr () is pretty nice. Will the following lines return from the beginning of the line to the first ? (the third argument to strstr () is only available for PHP 5.3.0):

 echo strstr($_SERVER["REQUEST_URI"], "?", TRUE); 

Or, if you want to stick to explode, you can use if list () . (2 indicates that no more than 2 elements will be returned by the explosion).

 list($url) = explode("?", $_SERVER["REQUEST_URI"], 2); echo $url; 

Finally, to use the initially available PHP parking ,

 $info = parse_url($_SERVER["REQUEST_URI"]); echo $info["scheme"] . "://" . $info["host"] . $info["path"]; 
+2
source share

EDIT:

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

I believe that PHP 5.4 comes with this feature, finally. Unfortunately, it will be some time before your average web host updates its version of PHP. My Ubuntu VPS doesn't even have it in the default repositories.

0
source share

All Articles