Home  >  Article  >  Backend Development  >  How to Retrieve Multiple Values for Same Parameter in $_GET in PHP?

How to Retrieve Multiple Values for Same Parameter in $_GET in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 01:23:30829browse

How to Retrieve Multiple Values for Same Parameter in $_GET in PHP?

Accessing Array Values in $_GET Variable

The $_GET superglobal array in PHP is commonly used to retrieve query string parameters from the URL. While it is typically expected that each parameter has a single value, it is possible to have multiple values for the same parameter.

In your case, when you send a request with multiple values for the "id" parameter (e.g., "http://link/foo.php?id=1&id=2&id=3"), the default behavior is for $_GET['id'] to return only the last value, which is 3.

Solution

To access multiple values for the same parameter in $_GET, you need to use the array notation. Instead of simply using $_GET['id'], you should use $_GET['id[]'] in your PHP code.

For example, consider the following URL:

http://link/foo.php?id[]=1&id[]=2&id[]=3

If you use $_GET['id'] to access the "id" parameter, you will still get only the last value (3). However, if you use $_GET['id[]'], you will get an array containing all the values: [1, 2, 3].

Example

<code class="php"><?php
if (isset($_GET['id[]'])) {
    $ids = $_GET['id[]'];
    foreach ($ids as $id) {
        // Do something with each id
    }
}
?></code>

This code will loop through each value in the "id[]" array and perform the desired operations.

The above is the detailed content of How to Retrieve Multiple Values for Same Parameter in $_GET 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