Beautifying PHP If Else Statements
If else statements are incredibly useful, but they're pretty messy. For example:
<?PHP
if(empty($value)) {
echo 'This value is empty';
}
else {
handleValue($value);
}
?>
That can be condensed into something simple like this:
<?PHP empty($value) ? echo 'This value is empty' : handleValue($value); ?>
Nice and clean!
Written by Brandon Anzaldi
Related protips
6 Responses

These are called ternary operators, very handy!
http://php.net/manual/en/language.operators.comparison.php

I have to agree that ternary operators are great when its a simple condition or expression but you cannot chain or nest them without causing confusion and might as well use it on a single line because if its multiple why not just use if statement? nonetheless, nice post cheers!

I wouldn't exactly call this Beautifying. But yes, ternary operators are very useful.

Thanks for the feedback guys!

Here's another way to write conditional statements:
<?PHP
if(empty($value)):
echo 'This value is empty';
else:
handleValue($value);
endif;
?>
This is also available with other statements like for, foreach or while.
They are very useful when you have to combine php with html in the same files.

@michd Very true. It's not that useful with complex if else statements. It's better with single conditional statements. And thanks for the tip about other languages. :)