Besides the long if/else notation, the one that you’ll use in most cases, there is also an shorten notation. In this case the ‘ternary operator’ (?) is used.

$var = [condition] ? [true] : [false];
  • [condition] -> The condition that has to be true.
  • [true] -> The result if the condition is true.
  • [false] -> The result if the condition is not true.

The above is thus another way of scripting for:

if([condition]) { $var = [true]; } else { $var = [false]; }

Example one: comparison with fruit

Voorbeeld 1: Een vergelijking met fruit

$input = 'apple';

$fruit = ($input == 'peach') ? 'peach' : 'banana';
echo $fruit; // 'banana'

Example two: Is there a name filled in?

$name = isset($_POST['name']) ? $_POST['naem'] : 'No name';
echo $name; // If $_POST['naam'] exists $name = $_POST['name'], if not, 'No name' will be displayed.

Example three: Direct display of variables

Instead of making first the variable and echo them afterwards you can do this in once.

$input = 'apple';

echo ($input == 'peach') ? 'peach' : 'banana'; // 'banana'

Example four: Using a php function

It is also possible to use a function in this notation.

$string = 'A string to hash';
$method = 'md5';

$hash = ($method == 'md5') ? md5($string) : sha1($string);

In this shorten if/else notation there is no possibility for a elseif statement. In case you do need to have a elseif statement you’ll have to use the long notation.

On this point you may scratch behind your ears and ask yourself why you’ll use this notation. Well, if you need to check some form values or something else this can be very useful and it will shorten your script!

Related Posts

Leave a Comment

Get your own Gravatar!
Your email will never be published!

Notify me of followup comments via e-mail

Top of Page