Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,238 members, 7,818,809 topics. Date: Monday, 06 May 2024 at 04:57 AM

Letz Learn Something 6 - The Ternary Operator - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Letz Learn Something 6 - The Ternary Operator (725 Views)

Letz Learn Something / Let's Learn Something 5: Flash Abuse / Let's Learn Something 2 - The Importance Of Specifying A Doc Type (2) (3) (4)

(1) (Reply)

Letz Learn Something 6 - The Ternary Operator by yawatide(f): 9:02pm On Jul 10, 2008
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"wink; ?>

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

(1) (Reply)

Suggest A Website That You Want To See Online / Need Help! Placing Ads On My Website A.s.a.p! / Free Software And Ebook Downloads

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 13
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.