Ternary Operator

A ternary or ? operator can evaluate to one of two different values based on a condition. The format is as follows: (condition) ? val1 : val2

The condition is evaluated. If it's true, the expression evaluates to val1. Otherwise it's val2.

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$today = "Monday";
$now = ($today == "Monday") ? "It's weekday": "It's a weekend.";
echo "$now<br />";
$value = -5;
$abs_value = ($value <0) ? -$value: $value;
echo "The absolute value is: $abs_value<br />";
?>
</p>
</body>
</html>

View the effect


Operators | Arithmetic | Increment/Decrement | Assignment | Comparison | Logical | Execution | String | Bitwise | Ternary | Operator Precedence
© 2008: Hann So
email: hso@voyager.deanza.edu