Rick
Rick

Reputation: 13490

How to breakup URL to keyvalue pair

I am looking to breaking up a URL to key value pair in PHP for example

/name/foo/location/bar/account/3449

Result would be something like this

array(name => "foo", location => "bar", account => "3449");

Current solution:

$urlPieces = explode('/', $_GET['q']);
$results = array();
$count = 0;
$keyName = "";
foreach ($urlPieces as $key=>$value) {
    if($count % 2 != 0){
       $results[$keyName] = $urlPieces[$count++];
    }else{
       $keyName = $value;
       $count++;
    }
}

Upvotes: 2

Views: 124

Answers (1)

Dan
Dan

Reputation: 9468

As I mentioned in the comments - $_GET['q'] does not exist because you don't have any query strings on that URL. Try this:

$url = strtok($_SERVER["REQUEST_URI"],'?'); //get the URL and remove query strings
$urlPieces = explode('/', $url); //create array from that URL
$count = 0;
$results = array();
foreach ($urlPieces as $key=>$value) { 
    if($count % 2 != 0){
       $results[$urlPieces[$key]] = $urlPieces[$count+1]; 
        //new array key is the current $key (aka $urlPieces[$key])
        //new array value is the value of the next key (aka $urlPieces[$count+1])
    }
    $count++;
}

The resulting array is $results. Note that this will only work properly if you have an even number of URI segments.

Upvotes: 2

Related Questions