Home >Backend Development >PHP Tutorial >How to Retrieve Multiple URL Parameters with the Same Name in PHP?
Retrieving Multiple Parameters with Same Name from a URL in PHP
URLs often contain multiple parameters with the same name. For instance, an OpenURL resolver may encounter URLs with multiple "rft_id" parameters. However, PHP's $_GET only retrieves the last value for each parameter.
To address this, we can utilize the following code snippet:
$query = explode('&', $_SERVER['QUERY_STRING']); $params = array(); foreach( $query as $param ) { // Prevent notice on explode() for missing '=' if (strpos($param, '=') === false) $param += '='; list($name, $value) = explode('=', $param, 2); $params[urldecode($name)][] = urldecode($value); }
This code will generate an array where each key is a parameter name and the corresponding value is an array of all values associated with that parameter.
In the provided OpenURL example:
// Sample URL $url = 'ctx_ver=Z39.88-2004&rft_id=info:oclcnum/1903126&rft_id=http://www.biodiversitylibrary.org/bibliography/4323&rft_val_fmt=info:ofi/fmt:kev:mtx:book&rft.genre=book&rft.btitle=At last: a Christmas in the West Indies. &rft.place=London,&rft.pub=Macmillan and co.,&rft.aufirst=Charles&rft.aulast=Kingsley&rft.au=Kingsley, Charles,&rft.pages=1-352&rft.tpages=352&rft.date=1871'; $query = explode('&', $url); $params = array(); foreach( $query as $param ) { if (strpos($param, '=') === false) $param += '='; list($name, $value) = explode('=', $param, 2); $params[urldecode($name)][] = urldecode($value); } var_dump($params);
Will output:
array( 'ctx_ver' => array('Z39.88-2004'), 'rft_id' => array('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323'), 'rft_val_fmt' => array('info:ofi/fmt:kev:mtx:book'), 'rft.genre' => array('book'), 'rft.btitle' => array('At last: a Christmas in the West Indies.'), 'rft.place' => array('London'), 'rft.pub' => array('Macmillan and co.'), 'rft.aufirst' => array('Charles'), 'rft.aulast' => array('Kingsley'), 'rft.au' => array('Kingsley, Charles'), 'rft.pages' => array('1-352'), 'rft.tpages' => array('352'), 'rft.date' => array('1871') )
This solution provides a straightforward way to handle multiple parameters with the same name in PHP URLs.
The above is the detailed content of How to Retrieve Multiple URL Parameters with the Same Name in PHP?. For more information, please follow other related articles on the PHP Chinese website!