Home > Backend Development > PHP Tutorial > How to Retrieve All Values for Duplicate URL Parameters in PHP?

How to Retrieve All Values for Duplicate URL Parameters in PHP?

Barbara Streisand
Release: 2024-11-30 07:43:11
Original
563 people have browsed it

How to Retrieve All Values for Duplicate URL Parameters in PHP?

Retrieving Multiple Parameters with Same Name from a URL in PHP

Problem:

When URLs contain multiple parameters with the same name, the PHP $_GET variable returns only the last value. This can be problematic, especially when the application requires access to all values for a given key.

Solution:

To retrieve all values for a given key, the following code can be used:

$query  = explode('&', $_SERVER['QUERY_STRING']);
$params = array();

foreach( $query as $param )
{
  // prevent notice on explode() if $param has no '='
  if (strpos($param, '=') === false) $param += '=';

  list($name, $value) = explode('=', $param, 2);
  $params[urldecode($name)][] = urldecode($value);
}
Copy after login

This code:

  • Explodes the query string into individual key-value pairs.
  • Decodes key and value names.
  • Initializes an associative array $params to store values.
  • Adds or appends values to the corresponding key in the $params array.

Result:

Executing this code on the provided URL parameters produces the following array:

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')
)
Copy after login

The above is the detailed content of How to Retrieve All Values for Duplicate URL Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template