randomehh
randomehh

Reputation: 27

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?

Upvotes: 1

Views: 2027

Answers (3)

user209850
user209850

Reputation: 1

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.

Upvotes: -1

G4Hu
G4Hu

Reputation: 328

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.

Upvotes: 0

newfurniturey
newfurniturey

Reputation: 38436

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).

Upvotes: 4

Related Questions