Ternary if else in PHP, condition, operator, without else, echo?

Ternary if else in PHP, condition, operator, without else, echo?

Here is a good example:

1
echo (2 == 3) ? 'x' :'y';

this will echo “y”.

You need to put echo in front, you can’t put echo inside the ternary statement.

Another example:

2
3
4
5
6
7
<?php
$var1 = 'America';
$var2 = 'Is great';
 
echo ($var1 === $var2)? 'It is not': 'It is';
?>

You can put the ternary if else to be a variable, like in this simple example:

3
4
5
6
7
8
9
10
<?php
$var1 = 'America';
$var2 = 'Is great';
 
$answer = ($var1 === $var2)? 'It is not': 'It is';
 
echo $answer;
?>

echo will return “It is”.

And an example with a function:

4
5
6
7
8
9
10
11
12
<?php
 
function test($color){
return ($color == 'blue') ? 'It is blue' : 'It is not blue';	
}
 
echo test("red");
 
?>

Looks like the else statement can’t be unset, meaning that you can skip putting the : sign. You can just put :”; So it will have an empty value there.

Another example with an input:

5
6
7
8
9
<?php
$var = (2 == 2) ? 'true' : 'false';
echo '<input name="input" type="text" value="'.$var.'">';
 
?>

Add a comment: