Jump to content

If GET variable empty then default value


Go to solution Solved by AbraCadaver,

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'];
Edited by thara

 

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.