logo
g Text Version
Auto
Beauty & Self
Books & Music
Career
Computers
Education
Family
Food & Wine
Health & Fitness
Hobbies & Crafts
Home & Garden
Money
News & Politics
Relationships
Religion & Spirituality
Society & Culture
Sports
Travel & Leisure
TV & Movies

dailyclick
Bored? Games!
Postcards
Astrology
Take a Quiz
Rate My Photo

new
English Garden
Costuming
Charity
Women's Fashion
Pop Music


dailyclick
All times in EST

Full Schedule
g
g PHP Site
Editor Wanted
BellaOnline's PHP Editor

g

The PHP Ternary Operator
Guest Author - Diane Cipollo

Like the PHP if and switch statements, the ternary operator (?) allows your program to ask questions and perform tasks based on the answer to those questions. The PHP ternary operator looks like a question mark (?) and the code has three parts. Let's take a look at an example and discuss those parts.

(expression) ? return_if_ture : return_if_false;

$var = ($test_var == "December") ? "Merry Christmas" : "It is not Christmas yet";


($test_var == "December")
(expression)
The first part of the code is the text expression. In the example, it is tested if the variable ($test_var) is equal to "December". The test expression is placed on the left side of the ? ternary operator.

"Merry Christmas"
return_if_true
The second part of the code is returned only if the test expression is a match. If the $test_var is equal to December, the variable $var will be set to "Merry Christmas". This part of the code follows the ? ternary operator.

:
The colon : separates the second part of the code from the third part of the code.

"It is not Christmas yet"
return_if_false
The third part of the code will be returned if the test expression is not a match. In this case the variable $var will be set to "It is not Christmas yet". This part of the code follows the : colon.

;
The line of code is completed with the ; semicolon.

As you can see this type of code can only be used when there are just two alternatives to a situation. Therefore the code is not as versatile as the if and switch statements. But it is a concise way to code this type of situation.





This site needs an editor - click to learn more!

RSS | Previous Features | Site Map


Content copyright © 2008 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.

Digg! g delicious Save to Del.icio.us

g


For FREE email updates, subscribe to the PHP Newsletter


Past Issues


print
Printer Friendly
bookmark
Bookmark
tell friend
Tell a Friend
forum
Forum
email
Email Editor

g features
Archives | Site Map

forum
Forum
email
Contact

Past Issues
memberscenter


vote
Driving Amount
Much more
Slightly more
Slightly less
Much less

g


| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2008 Minerva WebWorks LLC. All rights reserved.


BellaOnline Editor