DJ Mike's Tutorials: PHP, Ternary Operator

Conditional Statements

Ternary Operator

< ^ >

When used in PHP the ? is called a ternary operator. The ternary operator is like a simplified if statement and else statement combined. If tests an expression and returns one of two expressions separated by a colon. If the test expression is true, the result to the left of the colon is returned. If it is false, the result to the right of the colon is returned. The syntax looks like this:

<?
$output 
= ( test ) ? "if_true" "if_false";
?>

The ternary operator is useful when there are only two possible results to your test and if you like compact code. In the example below, I use the ternary operator to validate a password.

Show Code | Show Working Example
Show Code | Show Working Example


< ^ >


Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>