Nice urls, REQUEST_URI and array

Hi,

I have nice urls: /foor/var/id/2/

Please consider the following code:


$requestUri = explode("/",$_SERVER['REQUEST_URI']);

I have tried many ways to associate correctly my nice url in a key => value fashion, without success. I’m sure it must be fairly simple to someone with mroe experience.

:slight_smile:

which ones are the keys, and which ones are the values?


$requestUri = explode("/",$_SERVER['REQUEST_URI']);  
for ($i = 0; $i < count($requestUri); $i += 2) {
    ${$requestUri[$i]} = isset($requestUri[$i+1]) ? $requestUri[$i+1] : null;
}
var_dump($GLOBALS);

Start at 1, Remon. 0 will be the blank string before the first /.

Right, or we could remove all slashes at the start of the string, which I think is a bit nicer because it also avoids accidental double slashes problems.


$requestUri = ltrim('/', explode("/",$_SERVER['REQUEST_URI']));
for ($i = 0; $i < count($requestUri); $i += 2) {
    ${$requestUri[$i]} = isset($requestUri[$i+1]) ? $requestUri[$i+1] : null;
}
var_dump($GLOBALS);  

For completeness sake we could check if count($requestUri) %2 == 0 to see that each key has a value, but I’m not sure what to do if this is not the case, so I’ll leave that to the OP.