PHP Nested Triple Problem

I have nested ternary operators in my code:

$error = $fault_all ? "ALL" : $fault_twothirds ? "TWOTHIRDS" : $fault_onethird ? "ONETHIRD" : "UNKNOWN";
        echo 'STATEERROR: ' . $error . ';';

They are listed in the order of my preferences from left to right, so if $ fault_all and $ fault_twothird are true, I want "ALL" to be assigned $ error; The same thing if they are all true. If everything is false, then "UNKNOWN" must be assigned an error.

However, if any of them is true, only "ONETHIRD" is returned if a false "UNKNOWN" is returned. How can I return “ALL” and “TWELVE”?

0
source share
3 answers

, , , , if-elseif , , :

<?php
function state( $states ) {
    foreach( $states as $state => $current ) {
        if( $current ) {
            return $state;
        }
    }
    return 'UNKNOWN';
}

$states = array(
    'ALL' => $fault_all,
    'TWOTHIRDS' => $fault_twothirds,
    'ONETHIRD' => $fault_onethird
);

var_dump( state( $states ) );

, , :

<?php
$error = ( $fault_all ? "ALL" : ( $fault_twothirds ? "TWOTHIRDS" : ( $fault_onethird ? "ONETHIRD"  : "UNKNOWN" ) ) );
+1

( ), eachother if/else.

+1

This is a known issue. - veekun

Take, for example, the following nested triple ...

<?php 
$arg = 'T';
$vehicle = ( ( $arg == 'B' ) ? 'bus' :
           ( $arg == 'A' ) ? 'airplane' :
           ( $arg == 'T' ) ? 'train' :
           ( $arg == 'C' ) ? 'car' :
           ( $arg == 'H' ) ? 'horse' :
           'feet' );
echo $vehicle; 

prints 'horse'

As pointed out by @ berry-langerak, use the flow control function ...

Using the {array, structure} object is much more reliable ... IE

$vehicle = (empty( $vehicle) ?

    array(

    'B' => 'Bus',
    'A' => 'Airplane',
    'T' => 'Train',
    'C' => 'Car',
    'H' => 'Horse',

    ):

    NULL
 );

 $arg = 'T';

 $vehicle = (! empty($arg) ? $vehicle[$arg] : "You have to define a vehicle type");

 echo($vehicle);
+1
source

All Articles