In PHP the ternary operator has a short version.
expr1 ? expr2 : expr3;
changes into
expr1 ? : expr3;
The short version returns the result of expr1 on true and expr3 on false. This allows cool code that can populate variables based on their own current state. For example:
$employee = $employee ? : new Employee();
If $employee == null
or evaluates to false for any other reason, the code above will create a new Employee();
Otherwise the value in $employee
will be reassigned to itself.
I was looking for something similar in Java, but I could not find any similar use case of the ternary operator. So I am asking if is there such a functionality or something similar that can avoid one of the expressions of the ternary operator in order to reduce duplication.
The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.
Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.
It is called the nested ternary operator in Java.
The ternary operator (? :) It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement.
No, there is not. (A ternary operation requires, by definition, three operands)
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Source: The PHP Manual
Just like the one in Java but in Java you need to specify both outcomes:
The ternary if-else operator works with three operands producing a value depending on the truth or falsehood of a boolean assertion. It's form is as follows:-
boolean-exp ? value1 : value2
Sources:
Java specs on the ternary conditional operator
Official Java documentation
The Java.net Blogs
Also keep in mind that, unlike Java and every other popular language with a similar operator, ?:
is left associative in PHP. So this:
<?php
$arg = "T";
$vehicle = ( ( $arg == 'B' ) ? 'bus' :
( $arg == 'A' ) ? 'airplane' :
( $arg == 'T' ) ? 'train' :
( $arg == 'C' ) ? 'car' :
( $arg == 'H' ) ? 'horse' :
'feet' );
echo $vehicle;
prints horse
instead of train
(which is what you would expect in Java)
Sources:
http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/#operators
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With