Last Updated: October 11, 2021
·
2.134K
· caffeinewriter

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!

6 Responses
Add your response

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

over 1 year ago ·

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!

over 1 year ago ·

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

over 1 year ago ·

Thanks for the feedback guys!

over 1 year ago ·

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.

over 1 year ago ·

@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. :)

over 1 year ago ·