faqts : Computers : Programming : Languages : PHP : kms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 25 people (72%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

I know in C++ there is something similar to: "$foo?echo 'true':echo 'false';" Is there anything in php like this and what is it's syntax?

Nov 28th, 2001 19:37
Philip Olson, Mats Remman, feiy hy, Craig Fratrik,


Yes, the ternary operator is also available in PHP.  Here's an example 
use:
  $bgcolor = ($i++ % 2) ? '#ffffff' : '#000000';
Which behaves exactly like the following:
  if ($i++ % 2) {
    $bgcolor = '#ffffff';
  } else {
    $bgcolor = '#000000';
  }
A mention in the PHP Manual exists here:
  http://www.php.net/manual/en/language.expressions.php
  http://www.php.net/manual/en/language.operators.comparison.php
And for informational purposes (unrelated to this question), the % in 
the above example is called "Modulus" which is further explained here:
  http://www.faqts.com/knowledge_base/view.phtml/aid/783/fid/9