简体   繁体   中英

understanding nested ternary operators

I have this piece of code that is unclear to me, specifically the complex use of the ternary operators

if (!$byField && is_numeric($v)){ // by ID
$r=$fromRow?
$fromRow:
($v?
dbRow("select * from pages where id=$v limit 1"):
array()
);
}

if someone could explain how to evaluate the nested use of ternary operators

Using nested ternary operators in your code adds unnecessary complexity. For the same reason, it should not be used. Just use a normal if-else block instead. That's far more readable.

if (condition) {
    # code...
} 
else {
    # code...
}

To answer your question:

$r = $fromRow ? $fromRow : ( $v ? dbRow("..."): array() );

The above statement can be rewrote as follows:

if (!$byField && is_numeric($v))
{ 
    if ($fromRow) 
    {
        $r = $fromRow;
    }
    elseif ($v) 
    {
        $r = dbRow("select * from pages where id=$v limit 1"):
    } 
    else 
    {
        $r = array();
    }
}

As you can see, it's more readable.

Consider the following code:

<?php
    $a = true;
    $b = false;
    $c = true;

    echo (
        $a 
        ? 'A is true'
        : (
            $b 
            ? 'A is false, but B is true'
            : (
                $c 
                ? 'A is false, B is false, but C is true'
                : 'A, B and C are all false'
            )
        )
    );
?>

Which could easily be rewritten as so:

<?php
    if ($a) {
        echo 'A is true';
    } else {
        if ($b) {
            echo 'A is false, but B is true';
        } else {
            if ($c) {
                echo 'A is false, B is false but C is true';
            } else {
                echo 'A, B and C are all false';
            }
        }
    }
?>
if (!$byField && is_numeric($v)){ // by ID
  if ($fromRow) {
    $r = $fromRow;
  else if ($v) {
    $r = dbRow("select * from pages where id=$v limit 1"):
  } else {
    $r = array();
  }
}

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