8

What is the name of the following type of if/else syntax:

print $foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

I couldn't find any dedicated page in the php manual. I knew that it existed, because I've read a book (last year) with it, and now I found this post.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
SOMN
  • 351
  • 1
  • 3
  • 15

2 Answers2

14

This is called a ternary expression

http://php.net/manual/en/language.expressions.php

You should note, this is not an "alternate syntax for if" as it should not be used to control the flow of a program.

In the simple example of setting variables, it can help you avoid lengthy if statements like this: (ref: php docs)

// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

However it can be used other places than just simple variable assignent

function say($a, $b) {
    echo "{$a} {$b}";
}

$foo = false;

say('hello', $foo ? 'world' : 'planet');

//=> hello planet
maček
  • 76,434
  • 37
  • 167
  • 198
10

It's called the ternary operator - although many people call it the "?: operator" because "ternary" is such a seldom-used word.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Keep in mind that `?:` has a specific meaning, itself, as a shortcut for the longer syntax; `$dog = 'cat' ?: 'dog';` will result in $dog containing the string value: `cat`. It is identical to doing: `$dog = 'cat' ? 'cat' : 'dog';` or `if('cat') { $dog = 'cat'; } else { $dog = 'dog'; }` As such, I prefer just calling it the ternary operator. Or you could even call it the "short if" or "abbreviated if" syntax. – imkingdavid Dec 01 '12 at 23:58