Jump to content

If GET variable empty then default value


mastubbs

Recommended Posts

Hi All,

 

I have a script that relies on a numeric variable from GET. I am trying to figure out how to have a 'default' value if no GET value is passed in the url.

 

I have been trying to get it to work with if() but no joy:

$par2 = $_GET['par1']; 

if(empty($par2))
{ $par = 4; 
} $par = $par2;

So if a value for 'par1' is passed in the url then $par will be whatever that value is. However if no value is passed then the default value for $par should be 4. Unfortunately that code doesn't seem to work. If i pass no 'par1' value in the url i jest get a php error. Any tips on where im going wrong here would be much appreciated.

 

Thanks in advance for any help,

 

Matt

I think you have missed else part from your 'if' condition.

 

try this. 

if(empty($_GET['par1'])) {
    $par = 4;    
} else {
    $par = $_GET['par1'];    
}

In this case you can also use php ternary operator:

 

your code should be something similar to this using Ternary Operator

$par = (empty($_GET['par1'])) ? 4 : $_GET['par1'];

 

I think you have missed else part from your 'if' condition.

 

try this. 

if(empty($_GET['par1'])) {
    $par = 4;    
} else {
    $par = $_GET['par1'];    
}

In this case you can also use php ternary operator:

 

your code should be something similar to this using Ternary Operator

$par = (empty($_GET['par1'])) ? 4 : $_GET['par1'];

 

Whops yep i forgot the 'else', thanks.

 

Thanks also for introduction to ternary operator.

 

Matt

Ah... i have noticed a problem here. Sometimes the value of 'par1' will be 0.  The problem with the methods above is that they seem to assume that par1 = 0 is the same as empty. Is there a way to get it to recognise 0 as a number, but still default to '4' if empty ?

 

Thanks all for the help,

 

Matt

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.