How can one avoid repeating GET variables in a URL when appending a new variable in PHP?

When appending a new GET variable to a URL in PHP, you can avoid repeating existing GET variables by first checking if the URL already contains any GET variables. If it does, you can use the `parse_url` and `parse_str` functions to parse the URL and then add the new GET variable to the existing ones before reconstructing the URL.

// Example code to avoid repeating GET variables in a URL when appending a new variable
$url = 'http://example.com/page.php?existing_var=123';

// Check if the URL already contains GET variables
if (strpos($url, '?') !== false) {
    $urlParts = parse_url($url);
    parse_str($urlParts['query'], $query);
    $query['new_var'] = '456';
    $url = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . http_build_query($query);
} else {
    $url .= '&new_var=456';
}

echo $url;