Posts

How to write if else statement in a single line (compact if else statement) using PHP

Normal way of writing an if else statement

<?php

$result = '';

$count = 55;
$target = 70;

if($count >= $target) {
   $result = 'High';
} else {
   $result = 'Low';
}

?>

Now let’s see how the above can be written in a single line.

<?php

$result = '';

$count = 55;
$target = 70;

$result = ($count > $target) ? 'High' : 'Low';

?>

That’s it! Happy coding!