Dustin
Dustin

Reputation: 89

PHP GET Question: How do I set a variable value only if it's not in the query string?

I know how to get the value from the query string if the parameter exists:

$hop = $_GET['hop'];

But I also need to set a default value IF it's not in the query string. I tried this and it didn't work:

$hop = $_GET['hop'];

if ($hop = " ") {
  $hop = 'hardvalue';
};

Please help me handle the case where the query string has and does not have the "hop" parameter, and if it's present but not defined:

example.com/?hop=xyz

&

example.com/

&

example.com/?hop=

PS I don't know what I'm doing, so if you explain to me, please also include the exact code for me to add to my PHP page.

Upvotes: 1

Views: 1826

Answers (4)

mario
mario

Reputation: 145492

You already got the fiddly solutions. When working with URL or form parameters, you often want to treat the empty string or zeros as absent values too. Then you can use this alternative syntax:

$hop = $_GET["hop"]   or   $hop = "hardvalue";

It works because of the higher precedence of = over or, and is easier to read with extra spaces.

Starting from PHP 5.3 it's also possible to use:

$hop = $_GET["hop"]  ?:  "hardvalue";

The advantage here is that this syntax doesn't slurp up php notices, which are useful for debugging.

Upvotes: 1

nkorth
nkorth

Reputation: 1694

Actually, I would use

$hop = !empty($_GET['hop']) ? $_GET['hop'] : 'default';

Using empty() instead of isset() takes care of your third scenario, where the parameter is present but not defined.

Also, in if ($hop = " ") the = would need to be changed to ==. = assigns, == tests equality. The way you have it, the if-statement will always run, no matter what $hop equaled.

Upvotes: 1

whoughton
whoughton

Reputation: 1385

Thought about it a bit more and decided it should be a bit more robust:

$hop = 'hardvalue';
if (array_key_exists('hop', $_GET)) {
    if (!empty($_GET['hop'])) { $hop = $_GET['hop']; }
}

Upvotes: 2

Byron Whitlock
Byron Whitlock

Reputation: 53921

use array_key_exists

if (array_key_exists('hop', $_GET))
{
 // the key hop was passed on the query string.
 // NOTE it still can be empty if it was passed as ?hop=&nextParam=1

} 
else
{
 //the key hop was not passed on the query string.
}

Upvotes: 2

Related Questions