PHP: One Line If Statement (Ternary Operator)

I decided to see if there was a better way to write a simple if statement today, and of course, there was. It uses the Ternary Operator (?:). My if statement today was rather simple. I needed to find out if a variable was an object or not, and set a new variable accordingly. Here was my original if statement:


if (is_object($product)) {
    $id = $product->entity_id;
} else {
    $id = '';

You can write the same logic on one simple line like this instead:

$id = (is_object($product)) ? $product->entity_id : '';

Simply put, the statement is evaluated and if it is true, assign what comes after the question mark. If it is false, assign what comes after the colon.

So for all those simple if statements that you have to check something before you set a variable (or many other uses I’m sure), consider using the ternary operator and saving yourself some code.

This entry was posted in PHP. Bookmark the permalink.

Comments are closed.