Using a combination of:
- The behaviour of http_build_query() to remove parameters when passed null
- PHP array ‘union’ addition
gives a simple, yet powerful set of native GET parameter manipulation methods.
I have been using these for years but never come across them documented anywhere, hopefully they will be useful to someone.
Add/Update Parameter:
echo http_build_query(
[
'foo' => 'bar',
] + $_GET,
);
Add Parameter (if it is not already set):
echo http_build_query(
$_GET + [
'foo' => 'bar',
],
);
Remove Parameter:
echo http_build_query(
[
'foo' => null,
] + $_GET,
);
Toggle Parameter:
echo http_build_query(
[
'foo' => isset($_GET['foo']) ? null : 'on',
] + $_GET,
);