简体   繁体   中英

PHP _GET values in an array

I have list of items, after selecting them and pressing a submit button there's kind of a query in the url bar as such :

adrese-id=7&food-id=1&food-id=2&food-id=3&food-id=4

Trying to get all of the food IDs in an array but no luck so far, tried doing:

$ids = $_GET['food-id'];

but that just has the last value, which is 4...

How do I get those values in an array?

You have to name your field to indicate it's an "array". So, instead of food-id , append brackets to the end to make it food-id[]

For example:

<input type="checkbox" name="food-id[]" value="1"> Pizza
<input type="checkbox" name="food-id[]" value="2"> Cheese
<input type="checkbox" name="food-id[]" value="3"> Pepperonis

Accessing it in PHP will be the same, $_GET['food-id'] (but it will be an array this time).

In php the $_GET array has $key => $value pairs. The 'food-id' in this case is the $key . Because all your values (1,2,3,4) have the same key: 'food-id' the array looks like this:

$_GET = [
'food-id' => 1,
'food-id' => 2,
'food-id' => 3,
'food-id' => 4,
]

This will always be parsed with the last $key => $value pair being used:

$_GET = [
'food-id' => 4
]

The solution to this is always using unique keys in your arrays.

You really need to provide the HTML fragment that generates the values. However if you look at your GET request the values for food-id are not being submitted as an array which is presumably what you want. Your GET request should look more like:

adrese-id=7&food-id[]=1&food-id[]=2&food-id[]=3&food-id[]=4

which should give you a clue as to how your HTML form values should be named.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM