Understanding Nested Ternary Operators

I have this part of the code that I don’t understand, in particular, the complex use of the triple Operators

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

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

0
php
Sep 04 '13 at 11:00
source share
3 answers

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' ) ) ); ?> 

What can be easily rewritten like this:

 <?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'; } } } ?> 
+2
Sep 04 '13 at 11:06 on
source share
β€” -

Using nested ternary operators in your code adds unnecessary complexity. For the same reason, it should not be used. Use a regular if-else block instead. This is more readable.

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

To answer your question:

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

The above statement can be rewritten 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, this is more readable.

+3
04 Sep '13 at 11:04 on
source share
 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(); } } 
+1
Sep 04 '13 at 11:02
source share



All Articles