muttley91
muttley91

Reputation: 12684

How to Get The Value Which is being set with GET?

I'm using GET to obtain information (unsensitive, of course) and in a URL such as this: http://www.sample.com/foo.php?KEY=VALUE if I wanted to obtain the text "KEY" from that, is it possible?

Upvotes: 1

Views: 63

Answers (2)

Sampson
Sampson

Reputation: 268424

Search Array for Value, Return Key

You could use array_search, which functions similar to using array_keys with the second argument:

$array = array( "Name" => "Jonathan" );
$key = array_search( "Jonathan", $array );

echo $key; // Name

Note that when searching for strings in this manner, your search will be case-sensitive, so make sure you get the case correct. This will return the first key found that corresponds to your search value. If many keys are found, only the first will be returned.

Retrieve Array Keys in Array

If you want all of your keys, you can use array_keys. This returns an array of keys. From this, you could find the one you want, and then use it to grab the corresponding value from $_GET.

$array = array( "Name" => "Jonathan", "Site" => "StackOverflow" );
$aKeys = array_keys( $array );

print_r( $aKeys );

Which results in the following array:

Array
(
    [0] => Name
    [1] => Site
)

Retrieve Array of Keys for Search

You can provide an optional second value for this function as well, which is the value for which you would like to get the corresponding key. In the array above (and the same goes for $_GET) I can get the key used for "Jonathan" by searching for "Jonathan":

$array = array( "Name" => "Jonathan", "Site" => "StackOverflow" );
$aKeys = array_keys( $array, "Jonathan" );

print_r( $aKeys );

This results in the following array:

Array
(
    [0] => Name
)

Upvotes: 1

Nauphal
Nauphal

Reputation: 6182

Try this

foreach($_GET as $key => $value) {
echo $key; // will print 'KEY'
echo $value; // will print 'VALUE'
}

Upvotes: 3

Related Questions