How to Get PHP $_Get Array

How to get PHP $_GET array?

The usual way to do this in PHP is to put id[] in your URL instead of just id:

http://link/foo.php?id[]=1&id[]=2&id[]=3

Then $_GET['id'] will be an array of those values. It's not especially pretty, but it works out of the box.

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

How to pass an array via $_GET in php?

You can use the [] syntax to pass arrays through _GET:

?a[]=1&a[]=2&a[]=3

PHP understands this syntax, so $_GET['a'] will be equal to array(1, 2, 3).

You can also specify keys:

?a[42]=1&a[foo]=2&a[bar]=3

Multidimentional arrays work too:

?a[42][b][c]=1&a[foo]=2

http_build_query() does this automatically:

http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3"

http_build_query(array(
'a' => array(
'foo' => 'bar',
'bar' => array(1, 2, 3),
)
)); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3"

An alternative would be to pass json encoded arrays:

?a=[1,2,3]

And you can parse a with json_decode:

$a = json_decode($_GET['a']); // array(1, 2, 3)

And encode it again with json_encode:

json_encode(array(1, 2, 3)); // "[1,2,3]"

Dont ever use serialize() for this purpose. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.

How to get an array of data from $_POST

Using [] in the element name

Email 1:<input name="email[]" type="text"><br>
Email 2:<input name="email[]" type="text"><br>
Email 3:<input name="email[]" type="text"><br>

will return an array on the PHP end:

$email = $_POST['email'];   

you can implode() that to get the result you want:

echo implode(", ", $email); // Will output email1@email.com, email2@email.com ...

Don't forget to sanitize these values before doing anything with them, e.g. serializing the array or inserting them into a database! Just because they're in an array doesn't mean they are safe.

PHP Get URL Parameter and its Value

Why not using $_GET global variable?

foreach($_GET as $key => $value)
{
// do your thing.
}


Related Topics



Leave a reply



Submit