开发者

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

开发者 https://www.devze.com 2023-02-21 04:12 出处:网络
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\'

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, an开发者_如何学运维d 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.


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.
}


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']; }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号