Quantcast
Channel: Knowledge Sharing » PHP
Viewing all articles
Browse latest Browse all 3

IF Construct in One Line Using PHP

$
0
0

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
   statement

The general format of if construct is like shown below:

if (expr1) {
   //  statement if expr 1 true
} else if (expr2) {
   // statement if expr 2 true
} else {
   // statement if expr 1 and 2 false
}

You may find useful documentation about if construct, else and else if in php.net.

But how if you only need two condition to produce a word or digit, and then save it into a variable or just echo it? You may write it like shown below:

if ($status = '0')
   echo 'Draft';
else
   echo 'Published';

In code example above, you need to write four lines. Compare with code shown below:

echo $status == '0' ? 'Draft' : 'Published';

The syntax is show below

echo expr ? 'value if true' : 'value if false';

You may change echo with variable assignment such as:

$var = expr ? 'value if true' : 'value if false';

Easy right? It cuts down four lines into one line only.

No related posts.


Viewing all articles
Browse latest Browse all 3

Trending Articles