Search code examples
phpunset

How to keep some URL parameters and remove all others


I have a URL with a range of parameters:

locations.php?use_url=on&zipcode=Axminster%2C+Devon+EX13+5RZ&categories%5B0%5D=2&radius=30&checkboxnational=1&submit=loading+results...&resultbar=25&sortbar=distance&lat=50.77643440000001&lng=-2.9810417&swlat=50.7773526197085&swlng=-2.9814507999999478&nelat=50.7800505802915&nelng=-2.9749947000000247&outcode=EX13

I am currently using the unset() command to remove all parameters except for some base parameters such as 'lat', 'lng', 'swlat, 'swlng', via the following code:

$url = $_SERVER["REQUEST_URI"];
$x = $url;
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['outcode'],$params['checkboxnational']);
$string = http_build_query($params);

However, this morning I have realised that my unset() is looking way too long, because in reality I am trying to unset about 20 parameters and keep only about 5 parameters. And going forward I'll probably being adding more parameters to the URL, which increases the risk of errors being made. So what I'm now trying to do is write code that keeps these base parameters, and remove all other parameters without having to individually name all these other parameters. Is this possible?

I don't mind php or javascript, either way. As long as it gets the job done. I have searched high and low and all I can find is people wanting to remove certain parameters, not keep certain and remove all others. Many thanks.


Solution

  • If parameters you want are always the same (I mean, keys are the same), then just do this:

    $myWantedParams = array('first' => $params['first'], 'second' => $params['second'] ... );
    unset($params);
    

    Instead of thinking how to remove parameters, just focus on what you really need and take it.