2

I'm looking for a simple function which will remove blank or duplicate variables from a query string in PHP. Take this query string for example:

?input=timeline&list=&search=&type=&count=10&keyword=hello&from=&language=en&keyword=&language=en&input=timeline

As you can see there are two input=timeline and the language and keyword variables appear twice- once set and once not. Also there are lots of variables that are blank- list, search and type.

What function would clean the URL up to make:

?input=timeline&count=10&keyword=hello&from=&language=en

?

I've found functions that remove queries, or certain variables, but nothing that comes close to the above- I can't get my head round this. Thanks!

2 Answers 2

4

I'd suggest simply taking advantage of PHP's parse_str, but as you mentioned, you've got multiple keys that are the same and parse_str will overwrite them simply by the order they're given.

This approach would work to favor values that are not empty over values that are, and would eliminate keys with empty values:

$vars = explode('&', $_SERVER['QUERY_STRING']);

$final = array();

if(!empty($vars)) {
    foreach($vars as $var) {
        $parts = explode('=', $var);

        $key = $parts[0];
        $val = $parts[1];

        if(!array_key_exists($key, $final) && !empty($val))
            $final[$key] = $val;
    }
}

If your query were input=value&input=&another=&another=value&final=, it would yield this array:

[input] => value
[another] => value

...which you could then form into a valid GET string with http_build_query($final).

Sign up to request clarification or add additional context in comments.

Comments

3

"?" . http_build_query($_GET) should give you what you want. Since $_GET is an associative array any duplicate keys would already be overwritten with the last value supplied in the query string.

2 Comments

I love the simplicity of this one, but unfortunately it doesn't work for my situation. http_build_query does remove duplicates, but if the query was ?test=1&list=hello&list= the output would be ?test=1&list= Ideally I want a function that returns the last variable even if a duplicate is blank. Also, http_build_query doesn't remove the blank entries. I need the URL to be as clean as possible. Thanks.
http_build_query simply takes an array or object and turns its keys/properties and their values into a query string-formatted string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.