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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 04:26:11109browse

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

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

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&param2=value2&param1=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!

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