In web applications, URLs often contain multiple parameters to pass information to the PHP script. However, PHP's $_GET function typically returns only the last value for a given parameter. This can be problematic when multiple parameters with the same name are present in the URL.
Consider this example URL:
http://example.com/index.php?param1=value1¶m2=value2¶m1=value3
In this case, $_GET['param1'] would return "value3," overwriting the earlier value ("value1").
To handle this issue, the following code snippet can be used:
$query = explode('&', $_SERVER['QUERY_STRING']); $params = array(); foreach ($query as $param) { // To prevent errors, ensure each element has an equals sign. if (strpos($param, '=') === false) { $param .= '='; } list($name, $value) = explode('=', $param, 2); $params[urldecode($name)][] = urldecode($value); }
This code will create an associative array where each key corresponds to a parameter name, and each value is an array containing all the values associated with that parameter. For the example URL above, the resulting $params array would be:
array( 'param1' => array('value1', 'value3'), 'param2' => array('value2') )
By using this method, you can easily access all values associated with each parameter from the URL, regardless of whether the parameters occur multiple times.
The above is the detailed content of How to 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!