Gero
Gero

Reputation: 47

How to pass an array?

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

Thanks

Upvotes: 3

Views: 250

Answers (4)

Magnus Nordlander
Magnus Nordlander

Reputation: 373

You call the script with something like this:

http://www.example.com/script.php?foo[bar]=xyzzy&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.

Upvotes: 0

John Fiala
John Fiala

Reputation: 4581

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.

Upvotes: -1

Austin Hyde
Austin Hyde

Reputation: 27436

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>";
    }
?>

Upvotes: 0

Jed Smith
Jed Smith

Reputation: 15934

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.

Upvotes: 10

Related Questions