What is this alternative if the / else syntax is called in PHP?

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

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

I could not find the highlighted page in the php manual. I knew that it exists because I read a book (last year) with it, and now I have found this post .

+8
php
source share
2 answers

This is called a ternary expression.

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

It should be noted that this is not an “alternative syntax for if”, since it should not be used to control program flow.

In a simple example of setting variables, it can help you avoid lengthy ones if such statements look 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 in places other than simply assigning a variable.

 function say($a, $b) { echo "{$a} {$b}"; } $foo = false; say('hello', $foo ? 'world' : 'planet'); //=> hello planet 
+10
source share

It was called a ternary operator — although many call it the ?: Operator because “triple” is such a rarely used word.

+10
source share

All Articles