Promet Knowledge Sharing

Archive for the ‘PHP’ Category

Ternary Operator

without comments

Usually we use the following snippet of code to assign a value in a variable given a condition:

<?php
if (cond) {
v = value1
} else {
v = value2
}
?>


This code can be expressed using the ternary operator.

<?php
v = cond ? value1 : value2;
?>


Of course we can use the ternary operator with nested conditions.

<?php
v = cond ? (cond1 ? value11 : value12) : (cond2?:value21:value22);
?>


But that isn’t really an advisable option :)

Written by jun

December 11th, 2008 at 8:49 am

Posted in PHP, Tips

Tagged with