Setting default value: $var = (isset($var)) ? $_POST['var']

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikebr
Forum Contributor
Posts: 243
Joined: Sat Sep 28, 2002 7:05 am

Setting default value: $var = (isset($var)) ? $_POST['var']

Post by mikebr »

I am using a form script and want to check for the value of $val, it can be set either from a config file or from a hidden field in a form...

1# First I want to check the value doesn't exist or has been set in the config file
2# if not then check if it has been set in the form
3# then if not set a default value for $var

So to cut down on the if, elseif's I tried to do it as follows:

Code: Select all

$var = (isset($var)) ? $_POST['var'] : 'DEFAULT_VALUE';
unfortunately if the value $var is set the isset($var) in the above line doesn't seem to read that it has a value, nor does POST and it just sets it to 'DEFAULT_VALUE'

anyone any idea?

Thanks
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

You forgot to check if that variable was set in $_POST

Code: Select all

if (!isset($var))
{
    $var = isset($_POST['var']) ? $_POST['var'] : 'DEFAULT_VALUE';
}
mikebr
Forum Contributor
Posts: 243
Joined: Sat Sep 28, 2002 7:05 am

Post by mikebr »

Yep, that's seems to do the trick.

Thanks
Post Reply