Skip to content
Advertisement

Add, change, and remove GET parameters from query string

Let’s say the current query string is the following

$_SERVER['QUERY_STRING']:
apple=green&banana=yellow2&navi=blue&clouds=white&car=black

I need a function which can add and remove several parameters from the query string. For example:

echo ChangeQueryString('eyes=2&fingers=10&car=purple', 'clouds&apple');

should give

banana=yellow2&navi=blue&car=purple&eyes=2&fingers=10

So, not only should the function be able to add new parameters (eyes=2&fingers=10), but it should also change the ones which are already present (car=black => car=purple).

All these new and changed parameters could be passed in the first argument of the function. Separated by “&”.

The second argument of the function should pass all the keys of the parameters which should be removed from the query string, if present.

I only managed the first part which can add and replace parameters. But maybe somebody has a more efficient way, including the second argument for removing things from the query string.

Actually in the end I need the complete current URL. That’s why I added PHP_SELF. Though the removing part is not there yet…

function ChangeQueryString ($add, $remove) {

    if (empty($_SERVER['QUERY_STRING'])){

        $final_url = $_SERVER['PHP_SELF']."?".$add;

    } else {

        $query_string_url_addition = $_SERVER['QUERY_STRING'].'&'.$add;

        parse_str($query_string_url_addition, $query_array);

        $final_url = $_SERVER['PHP_SELF']."?".http_build_query($query_array);

    }

    return $final_url;

}

Advertisement

Answer

function changeQueryString($queryStr, $updateStr, $removeStr) {
    parse_str($queryStr, $queryArr);
    parse_str($updateStr, $updateArr);
    parse_str($removeStr, $removeArr);
    $changedArr = array_merge($queryArr, $updateArr);
    foreach($removeArr as $k => $v) {
        if(array_key_exists($k, $changedArr)) {
            unset($changedArr[$k]);
        }
    }
    return http_build_query($changedArr);
}

$str = 'apple=green&banana=yellow2&navi=blue&clouds=white&car=black';
$changedQuery = changeQueryString($str, 'eyes=2&fingers=10&car=purple', 'clouds&apple');
var_dump($changedQuery);

This should work for you, utilizing parse_str(), array_merge() and http_build_query()

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement