Remove query parameter from URL in PHP

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

Remove query parameter from URL in PHP

How can I remove a parameter from URL query, and display the query string without the removed parameter?
For example, i have this URL:

Code: Select all

domain.net/folder/file.php?x=2&y=3&z=1
I want to remove the "y" parameter and show this query:

Code: Select all

x=2&z=1

Admin Posts: 805
You can use the queryToArray() function from the following example to make an array from URL query parameters.
With unset() remove the parameter you want from array.
Then, apply the http_build_query() function to re-build the query string.

Code: Select all

// Parse out url query string into an associative array
// @param $url String
// @return Array
function queryToArray($url){
  $qry = parse_url($url, PHP_URL_QUERY);
  parse_str($qry, $re);
  return $re;
}

$url ='domain.net/folder/file.php?x=2&y=3&z=1';
$ar_qry = queryToArray($url);

//to see the array
var_export($ar_qry); // array('x'=>'2', 'y'=>'3', 'z'=>'1')

//rebuild and show query string wthout the $except parameter
$except ='y';
unset($ar_qry[$except]);
$qry = http_build_query($ar_qry);

echo $qry; //x=2&z=1