Home >Backend Development >PHP Tutorial >How Can I Retrieve Multiple Parameters with the Same Name from a URL in PHP?

How Can I Retrieve Multiple Parameters with the Same Name from a URL in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 16:18:11284browse

How Can I Retrieve Multiple Parameters with the Same Name from a URL in PHP?

Retrieving Multiple Parameters with the Same Name from a URL in PHP

When handling URLs containing multiple parameters with the same name, PHP's default behavior using $_GET only returns the last value assigned. To access all values for a given key, consider the following approach:

  1. Parse the Query String: Use explode to split the query string into individual parameters.
$query = explode('&', $_SERVER['QUERY_STRING']);
  1. Initialize an Array: Create an array to store the parameters.
$params = array();
  1. Extract Parameter Name and Value: Iterate through the parameters and extract the name and value using explode.
foreach ($query as $param) {
  // Handle null value with '='
  if (strpos($param, '=') === false) $param += '=';

  list($name, $value) = explode('=', $param, 2);
}
  1. Decode and Store in Array: Decode the extracted parameters and add them to the array, creating an array for parameters with multiple values.
  $params[urldecode($name)][] = urldecode($value);
}

Using this approach, you can access the multiple parameter values as follows:

print_r($params['rft_id']);
// Array ('info:oclcnum/1903126', 'http://www.biodiversitylibrary.org/bibliography/4323')

The above is the detailed content of How Can I Retrieve Multiple Parameters with the Same Name from a URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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