How to build ternary if/else without else?

Hey

I’m trying to build a ternary if/else statement for checking if a POST var is set.
But it gives me an error if I leave the else field empy or remove it.
How could this be done?

I basically want:
No else.


if (!isset($_POST['firstname'])) {
$firstname = $_POST['firstname']
}

$firstname = (!isset($_POST['firstname'])) ? $_POST['firstname'] : ;

You cannot build a ternary operator with only one expected result. Its simple Boolean logic, it just returns two values.

I would suggest you just stick with the first if/else statement you have. Besides using ternary operators can be harder to read in comparison to the standard if/else statements.


$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : '';

This will assign a value submitted from form if it is set otherwise it will put a empty string.

I you really want to use the ternary operator without specifying the else, wait for php6, it’s in there :nod:

It’s actually in 5.3. :wink:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Sadly…$a = isset($b) ?: $c; Returns TRUE when I want $b. :frowning:
I suppose I could drop isset but that just feels like bad mojo.

Please consider using PHP’s filter_input method.


$firstname = filter_input(INPUT_POST, 'firstname');

There’s also a wide variety of validation and sanitisation filters that you can apply to it too.