简体   繁体   中英

Understanding PHP's ternary operator

I understand whiles, if s, for s, case s, array s, function s, and other syntactic constructs and my coding experience is 70's style Fortran and T-SQL.

Now I'm trying to understand PHP, but it occasionally seems to compress several statements into one obfuscating line of code. What's the expanded equivalent of the following single line of PHP below?

$start = gt("start") === false ? 0 : intval(gt("start"));

It is a ternary operator . They're usually of the following format:

expr1 ? expr2 : expr3;

Which means:

if expr1 then return expr2 otherwise return expr3

It can be visualized as follows:

Your code can be rewritten as:

if (gt("start") === false) {
    $start = 0;
} else {
    $start = intval(gt("start"));
}

It can improved as follows, to avoid an extra function call:

if (($result = gt("start")) === false) {
    $start = 0;
} else {
    $start = intval($result);
}

This ? is known as the ternary operator. It is a shorthand, eg

$x = a ? $b : $c; // where 'a' is some expression, variable or value

could also be written:

if (a) {
  $x = $b;
}
else {
  $x = $c;
}

Essentially, if expression a evaluates equal to TRUE , then the ternary operator returns b , otherwise it returns c .

Others have posted answers that do a good job of explaining the basics of how a ternary operator works, but to visualize what a ternary is versus an if / else you can do the following. Look at your example:

$start = gt("start") === false ? 0 : intval(gt("start"));

Now let's make it one line using if / else :

if (gt("start") === false) { $start = 0; } else { $start = intval(gt("start")); }

When you see it lined up like that the immediate take-away—beyond the basic structure—is you must set $start = within each conditional.

So knowing that, them main benefit of a ternary operator is quick if / else logic to assign a value to a single variable.

The convenience of this from a coding standpoint is one can quickly disable that logic by just commenting out one line while debugging instead of having to comment out multiple lines of an if / else .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM