GET parameter manipulation with PHP

Using a combination of:

  1. The behaviour of http_build_query() to remove parameters when passed null
  2. 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,
				);
			
		
Load Comments...