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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With