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
Release: 2024-12-04 16:18:11
Original
313 people have browsed it

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']);
Copy after login
  1. Initialize an Array: Create an array to store the parameters.
$params = array();
Copy after login
  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);
}
Copy after login
  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);
}
Copy after login

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

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