TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Nested Ternary = Fail (http://www.talkphp.com/absolute-beginners/5069-nested-ternary-fail.html)

delayedinsanity 10-29-2009 06:02 AM

Nested Ternary = Fail
 
Hmm. It's times like this that the coffee isn't fixing my problem, so I'm going to post in Absolute Beginners.

Can somebody spot the error in this nested ternary that I'm missing (and don't say the error is using a ternary, I'll poke you in the eye)? The preceding operation is there as a test and produces the desired result. The nested version is producing a fail. Fail!

php Code:
echo isset( $one[$i]['timestamp'] ) ? $one[$i]['timestamp'] : 'fail';
echo ' :: ';

$timestamp = isset( $one[$i]['timestamp'] )   ? $one[$i]['timestamp'] :
             isset( $two[$i]['timestamp'] )   ? $two[$i]['timestamp'] :
             isset( $three[$i]['timestamp'] ) ? $three[$i]['timestamp'] :
                                                    'fail';
die( $timestamp );

ioan1k 10-29-2009 11:52 AM

You need to enclose each level

PHP Code:

isset( $one[$i]['timestamp'] )  ? $one[$i]['timestamp'] : ( isset( $two[$i]['timestamp'] )   ? $two[$i]['timestamp'] : ( isset( $three[$i]['timestamp'] ) ? $three[$i]['timestamp'] : 'fail')); 


delayedinsanity 10-29-2009 04:34 PM

Ah. Doesn't quite look as pretty at that point. S'too bad. (That's what I get for reading a post on stack overflow as php specific that was actually language agnostic)

Rhinos 11-01-2009 08:57 PM

It doesn't look that bad with the parenthesis. Also I think indenting each ternary statement may improve readability also.


PHP Code:

$timestamp = (isset( $one[$i]['timestamp'] )   ? $one[$i]['timestamp'] :
               (isset( 
$two[$i]['timestamp'] )   ? $two[$i]['timestamp'] :
                 (isset( 
$three[$i]['timestamp'] ) ? $three[$i]['timestamp'] :
                   
'fail'
             
))); 



All times are GMT. The time now is 01:18 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0