views:

85

answers:

4

Hello!

How could I pass an array with PHP by GET method?

Thanks

+9  A: 

In your query string (or POST data, it doesn't really matter), you should end up with this:

http://example.com/myscript.php?foo[]=1&foo[]=2&foo[]=3

PHP will parse that into $_GET["foo"], and it will be an array with the members 1, 2, and 3. How you mangle that from a form is up to you. In the past, I've named different checkboxes "check[]", for example.

Jed Smith
A: 

Do you mean like through a form?

<form method="GET" action="action.php">
    <input type="text" name="name[]">
    <input type="text" name="name[]">
    <input type="submit" value="Submit">
</form>

Notice the name attribute has [] in it.

Then in your php:

<?php
    $names = $_GET['name'];
    foreach($names as $name) {
        echo $name . "<br>";
    }
?>
Austin Hyde
Yes, I want to do it through form (with checkboxes) but this solution didn't work :/
Gero
A: 

As an aside, instead of passing the array by GET, it might make more sense to store the array in the $_SESSION and get it out again later.

John Fiala
A: 

You call the script with something like this:

http://www.example.com/script.php?foo[bar]=xyzzy&amp;foo[baz]=moo

This will result in the following array in $_GET:

array(1) { ["foo"]=> array(2) { ["bar"]=> string(5) "xyzzy" ["baz"]=> string(3) "moo" } }

You can also leave out the key names in order to get regular array indexing.

Magnus Nordlander
"Notice: Undefined index: category" I get this
Gero
Exactly what query string are you using, and how are you accessing it?
Magnus Nordlander
<input type="checkbox" name="category[]" value="1" /> <input type="checkbox" name="category[]" value="2" /> <input type="checkbox" name="category[]" value="3" /> <input type="checkbox" name="category[]" value="4" />This is the form and I try to print it out with print_r
Gero
And you're using print_r($_GET['category']) to print? If you haven't checked any of the boxes, this is expected behavior. If you've checked some of the boxes, you may wish to add this, and more of the code to your original question.
Magnus Nordlander