Letz Learn Something 6 - The Ternary Operator

A Member? Please Login  
type your username and password to login
Date: August 22, 2008, 02:08 AM
232274 members and 132487 Topics
Latest Member: rmbwmaytk
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Webmasters (Moderator: uspry1)  |  Letz Learn Something 6 - The Ternary Operator
Pages: (1) Go Down Send this topic Notify of replies
Author Topic: Letz Learn Something 6 - The Ternary Operator  (Read 45 views)
yawa-ti-de (f)
Letz Learn Something 6 - The Ternary Operator
« on: July 10, 2008, 09:02 PM »

Suppose you wanted to test a condition like so:
if(bla) then
    print A
else
    print B
end if

Pretty basic stuff.  But how many lines is that? Further more, imagine if you had to do this 100 times.  I am sure your head is reeling at that thought right now.  So is there a better and efficient way?  I would say yes.  The solution would be the ternary operator.  With this operator, code like so:
<?php
    if(bla) {
?>
        print A
<?php
    } else {
?>
        print B
<?php
    }
?>

could easily be rewritten as:
<?php echo (bla ? "A" : "B"); ?>

Of course, this is an over-simplified piece of code but hopefully, you get the point.  For example, I use this all the time to determine what parts of my navigation menus to highlight on a given page, based on the URI.

Now, isn't that much easier? Wink

Did you find this useful?  Letz LEARN something!  There are 15 other short and easy lessons I have compiled into an Ebook.  You can email me at yawatide at yahoo dot com for details on how to obtain your copy.

Thanks
 Earn Money Owning And Running Your Own Autoresponder Service  Help! Please  Designing Website In A Jiffy  Page 2
Pages: (1) Go Up Send Topic to Friend by E-mail Reply 
Google
 
Web www.nairaland.com
Sections: TV/Movies (2) Music/Radio (2) Celebrities Job Talk Jobs/Vacancies (2) Career Talk Romance Books Politics Sports Fashion Travel
Health Schooling Religion General(2) Business Webmaster Programming Computers Phones Cars & Trucks

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.