Created
August 1, 2025 02:24
-
-
Save patricknelson/f15909c38e1f6067d7da9dbcfe49eba5 to your computer and use it in GitHub Desktop.
Allows you to easily modify an existing URL's query string parameters, overriding or simply adding new (while preserving existing parameters, if desired).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Allows you to easily modify an existing URL's query string parameters, overriding or simply adding new (while | |
* preserving existing parameters, if desired). | |
* | |
* @param string $url URL you wish to update. | |
* @param array $params Array of key/value combos. Set value to null to REMOVE the parameter. | |
* @param bool $override Indicates if this should override parameters or not. | |
* @return string | |
*/ | |
function updateQueryString($url, $params = [], $override = true) { | |
// Get existing parameters from the provided URL. | |
$urlParts = explode("?", $url); | |
$origParams = []; | |
if (!empty($urlParts[1])) parse_str($urlParts[1], $origParams); | |
// Setup new parameters (depending on override setting). | |
if ($override) { | |
$params = array_merge($origParams, $params); | |
} else { | |
$params = array_merge($params, $origParams); | |
} | |
// Remove any null parameters (but allow other falsey values, e.g. 0). | |
$params = array_filter($params, function($val) {return $val !== null;}); | |
// Rebuild query string and setup with URL. | |
$url = $urlParts[0]; | |
if (count($params) > 0) $url .= "?" . http_build_query($params); | |
return $url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment