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;
Keywords
Related Questions
- How can PHP developers troubleshoot issues with error reporting and exception handling on different server environments?
- What steps can be taken to troubleshoot and resolve issues related to character encoding discrepancies in PHP scripts interacting with MySQL databases?
- How can PHP developers troubleshoot and identify the source of output before PDF generation in their scripts?