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?
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().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With