Connection keep-alive
Connection keep-alive

Reputation: 11

How to make $_GET read the first variable with the same key?

URL: http://example.com/?var=foo&var=bar

How to make PHP set $_GET['var'] as "foo" and not "bar", without parsing manually $_SERVER['QUERY_STRING']? Maybe there is some option in the php.ini file?

Upvotes: 0

Views: 197

Answers (4)

khalid J-A
khalid J-A

Reputation: 614

update link to http://localhost/index.php?var[]=foo&var[]=bar

<?php
$foo=$_GET["var"][0];
echo $foo;//foo
print_r($_GET);//full array
?>

Upvotes: 0

user10226920
user10226920

Reputation:

terrible idea, but i was bored:

$url="http://example.com/?var=foo&var=bar";

$x=parse_url($url, PHP_URL_QUERY); //get the query string

$x=explode('&',$x); //break on &
$x=explode('=',$x[0]); //break on =
echo $x[1]; // =foo

Upvotes: 0

Dellowar
Dellowar

Reputation: 3352

No built in way to do this. PHP's $_GET wasn't designed for this practice, for it is an uncommon one. I recommend against it.

Upvotes: 0

Jim Wright
Jim Wright

Reputation: 6058

Unfortunately in PHP you cannot do this. You should use an array:

http://example.com/?var[]=foo&var[]=bar

You will get the following in PHP:

$_GET['var'] = ['foo', 'bar']

You will find this is different in other languages such a golang where your first example will actually get the same result.

You can find a brilliant answer on this answer.

Upvotes: 4

Related Questions