Ternary Conditional Syntax


/ Published in: PHP
Save to your folder(s)

Condition = The condition which must be met.
True = Executed if the condition is met.
False = Executed if the condition failes.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. $var = [condition] ? [true] : [false];
  4.  
  5. /* the above statement is the same as this more verbose syntax: */
  6.  
  7. if (condition) {
  8. $var = [true];
  9. } else {
  10. $var = [false];
  11. }
  12.  
  13. //Example
  14.  
  15. $isNew = false;
  16. $output = $isNew ? 'New' : 'Not New';
  17. print($output); // ='Not New';
  18.  
  19. $isNew = true;
  20. $output = $isNew ? 'New' : 'Not New';
  21. print($output); // ='New';
  22.  
  23. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.