Concise notation of if conditions in PHP

Краткая запись условий if else в PHP

Brief entry: expression ? true_value : false_value … This is usually called a ternary operator. The word comes from the Latin ternārius – consisting of three, triple. Consisting of three parts, components. See examples in the full post.

How to write a concise if else condition in PHP

Conditional operator ( ? : ) is a compact form of a condition statement if

To write a short version of the condition if () else { } use the conditional operator ( ? : )

Examples of using the ternary operator

Let’s check the value of the variable $ a and print the result.

Complete record:

if ( $a < 0 ) {
    echo "число отрицательное"; 
} else {
    echo "число положительное";

Brief entry:

if ( $a < 0 ) echo "число отрицательное" :  echo "число положительное";

Another option for a short entry, with the placement of a short condition inside the structure echo:

echo 'Число '.($a < 0 ? 'отрицательное' : 'положительное');

Write in the comments – you are a supporter or an opponent of the use of short conditions and the ternary operator.

Leave a Reply

Your email address will not be published.