Bob Crabb Posted February 22, 2009 Posted February 22, 2009 Good Grief, this had me chasing my tail for a while this evening. Some of you more experienced PHP coders have probably run into it, but it is the first time that I have attempted to use nested tertiary operators, so I thought that I would share my experience. What I was trying to accomplish was fairly simple. I wanted to have the greeting on a page change depending upon whether it is morning, afternoon or evening. The different phrases are in a language array, and the array keys for the phrases are 'm' for the morning message, 'a' for afternoon, and 'e' for evening. So I needed to evaluate the hour to set the key to the right value. Of course, I could use a series of if, elseif statements, but I wanted to do this in a single line using a tertiary operator. I thought that this would work: > $hour = date(G); $key = ($hour >= 17)? 'e' : ($hour >= 12)? 'a' : 'm'; I thought that if the hour was 17 or higher the first condition shold be true, and no further evaluation would occur. BUT, what happens instead is the second condition is evaluated, therefore a $hour value of greater than or equal 17 in this case returns 'a'. I finally found that in order for this operation to behave as I had expected, the entire second condition, ie the false result of the first condition, must be enclosed in parenthesis, like this: > $hour = date(G); $key = ($hour >=17)? 'e' : (($hour >= 12)? 'a' : 'm'); Well, I try to learn something new every day, so I guess I can call it quits for the day, and go veg out in front of the television. Quote
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.