PHP: get array element
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 re开发者_如何学编程ally 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.
Take a look at this previous question.
Hoohaah's suggestion of using strstr() is quite nice. The following will return from the beginning of the string until the first ?
(the third argument for strstr() is only available for PHP 5.3.0 onward):
echo strstr($_SERVER["REQUEST_URI"], "?", TRUE);
Or if you want to stick with explode, you can make use if list(). (The 2 indicates that at most 2 elements will be returned by explode).
list($url) = explode("?", $_SERVER["REQUEST_URI"], 2);
echo $url;
Finally, to use the natively available PHP URL parsing;
$info = parse_url($_SERVER["REQUEST_URI"]);
echo $info["scheme"] . "://" . $info["host"] . $info["path"];
EDIT:
echo current(explode("?", $_SERVER["REQUEST_URI"]));
I believe PHP 5.4 comes with this feature, at long last. Sadly, it will be a while before your average web host updates their PHP version. My Ubuntu VPS doesn't even have it in the default repos.
精彩评论