PHP short-hand IF/Else statement

Share/Save

Let’s keep it simple:

Regular way:

if (statement) {
  $variable = "return this if true";
}
else {
  $variable = "return this if false";
}

Short way:

$variable = (statement) ? "return if true" : "return if false";

And this is how it works: statement ? if-true : if-false

Share/Save

One Response to “PHP short-hand IF/Else statement”

  1. It’s hard to find a lot of information on this (and if there are other similar statements), but I noticed that it’s more formally known as a ternary statement! http://en.wikipedia.org/wiki/Ternary_operation

Leave a Reply

* Required fields.