Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PHP $_GET array?

Tags:

php

Is it possible to have a value in $_GET as an array?

If I am trying to send a link with http://link/foo.php?id=1&id=2&id=3, and I want to use $_GET['id'] on the php side, how can that value be an array? Because right now echo $_GET['id'] is returning 3. Its the last id which is in the header link. Any suggestions?

like image 569
faya Avatar asked Dec 02 '09 14:12

faya


People also ask

Is $_ get an array?

Now that we know how to pass the variables in the URL, we're going to get it in PHP using $_GET. $_GET is a built-in variable of PHP which is an array that holds the variable that we get from the URL.

How does $_ GET work in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL.

Can PHP send array request get?

You can pass an associative array to http_build_query() and append the resulting string as the query string to the URL. The array will automatically be parsed by PHP so $_GET on the receiving page will contain an array.

How do I get one element from an array?

indexOf() The indexOf() method returns the first index at which a given element can be found in an array. It returns -1 if the element does not exist in the array.


2 Answers

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.

like image 112
Jordan Running Avatar answered Oct 13 '22 07:10

Jordan Running


You could make id a series of comma-seperated values, like this:

index.php?id=1,2,3&name=john

Then, within your PHP code, explode it into an array:

$values = explode(",", $_GET["id"]); print count($values) . " values passed."; 

This will maintain brevity. The other (more commonly used with $_POST) method is to use array-style square-brackets:

index.php?id[]=1&id[]=2&id[]=3&name=john

But that clearly would be much more verbose.

like image 45
Sampson Avatar answered Oct 13 '22 07:10

Sampson