Home >Backend Development >PHP Tutorial >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!