Jump to content

Ternary Operator ( ? : )


timothyarden

Recommended Posts

Hi,
Just wanted to check with everyone that I am getting the Logic right with the use of the Ternary ? : Operator

isset( $Files ) ? isset( $Directories ) ? __DisplayResults__( $Files, $Directories ) : __DisplayResults__( $Files, NULL ) : isset( $Directories ) ? __DisplayResults__( NULL, $Directories ) : $error = "Neither Directories or Folders are set";

So that should do the same as

            if( isset( $Files ) && isset( $Directories ) ){
                __DisplayResults__( $Files, $Directories );
            } elseif( isset( $Files ) ){
                __DisplayResults__( $Files, NULL );
            } elseif( isset( $Directories ) ){
                __DisplayResults__( NULL, $Directories );
            } else {
                 $error = "Neither Directories or Folders are set"
            }

Thanks :)

Link to comment
https://forums.phpfreaks.com/topic/282399-ternary-operator/
Share on other sites

Nevermind, managed to figure it out on my own, needed Parenthesis

Example:
$Files = TRUE;
$Directories = NULL;
    
isset( $Files ) ? ( isset( $Directories ) ? $a = "Files & Directories" : $a = "Files" ) : ( isset( $Directories ) ? $a = "Directories" : $a = "Neither" );
    
echo $a;
Link to comment
https://forums.phpfreaks.com/topic/282399-ternary-operator/#findComment-1450966
Share on other sites

The problem with what you've done is that it makes the code much harder to read. When you come back to this in the future, or if somebody else has to work with your code, your nested ternary operations require much more effort to review. If instead you did something like this, anyone can understand what is going on in about 1 second:

$f = isset( $Files ) ? $Files : NULL;
$d =  isset( $Directories ) ? $Directories : NULL;

if( is_null($f) && is_null($d) ){
	$error = "Neither Directories or Folders are set";
}else{
	__DisplayResults__( $f, $d );
}
Link to comment
https://forums.phpfreaks.com/topic/282399-ternary-operator/#findComment-1450969
Share on other sites

Yeah, I wanted a one line solution though haha
the parenthesis work fine and make it easily readable

also unless Im not reading your code right it would need 2 more elseif conditions - I just found it much simpler to it in the one line instead of 10

thanks for the tip though :)

Link to comment
https://forums.phpfreaks.com/topic/282399-ternary-operator/#findComment-1451011
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.