1

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?

4
  • Please add the HTML which is generating the request. Commented Dec 18, 2017 at 16:21
  • Have your tried $_GET[] yet? Commented Dec 18, 2017 at 16:22
  • 6
    Possible duplicate of How to get multiple parameters with same name from a URL in PHP Commented Dec 18, 2017 at 16:22
  • 1
    Possible XY Problem. Commented Dec 18, 2017 at 16:23

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.