Main Content

Smart English Output - via PHP and Perl ? : operator

Archive - Originally posted on "The Horse's Mouth" - 2007-05-18 08:25:17 - Graham Ellis

It's smart to have your program say "there IS in stock" or "there ARE 2 in stock" ... but if you write your code using an "if" and "else" type structure it can become quite verbose.

The ? ... : operator - available in many languages including C, Perl and PHP - allows you to write a single "if,else" line in a much shorter form:

{condition} ? {value if true} : {value if false}

Here's an subtle example of this operator in use - an image from our pricing for a two day public course:



where you'll note "room" and "rooms". The code, where $ns is a variable containing the number of students:

$rlet = ($ns==1) ? "":"s";
$pricing[$ns] .= "<b>With hotel room$rlet<b><br>";