ngreenwood6 Posted July 23, 2010 Share Posted July 23, 2010 I have a loop like this: <?php for($i=0;$i<7;$i++){ $class = ($i==0) ? 'cal_item cal_item_first' : ($i==6) ? 'cal_item cal_item_last' : 'cal_item'; echo $class; } ?> I dont see anything wrong with it but for some reason when it hits the first item it is saying cal_item_last instead of cal_item_first. Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/208727-ternary-operator/ Share on other sites More sharing options...
ngreenwood6 Posted July 24, 2010 Author Share Posted July 24, 2010 I actually just figured it out. When I put the second statement in parenthesis it then works....Can anyone explain...I would have thought it would have stopped when it met the first condition but it seems like it was checking the second no matter what for some reason? <?php for($i=0;$i<7;$i++){ $class = ($i==0) ? 'cal_item cal_item_first' : (($i==6) ? 'cal_item cal_item_last' : 'cal_item'); echo $class.'<br />'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/208727-ternary-operator/#findComment-1090466 Share on other sites More sharing options...
Alex Posted July 24, 2010 Share Posted July 24, 2010 There's an example in the manual that deals exactly with this. See "Example #3 Non-obvious Ternary Behaviour" on this page. Quote Link to comment https://forums.phpfreaks.com/topic/208727-ternary-operator/#findComment-1090467 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.