Reputation: 335
Could under any circumstances those two produce different results, or in general, is there any difference (performance, etc...) between them:
$r = this() ?: that();
and...
$r = this() or that(); // $r = this() || that();
Assuming there's no difference, which one would you suggest using and why?
Upvotes: 0
Views: 99
Reputation: 21671
Hi I suggest you read the documentation as it's all there
http://php.net/manual/en/language.operators.logical.php
http://php.net/manual/en/language.operators.precedence.php
And
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
As I understand it the main difference is the order of precedence, however I find this to rarely ( never ) be a real issue, as I never mix them. Even then there is this bit
Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation.
Which if I am thinking right is only relevant to how the PHP interpreter sees them, and really has no Bering on userland code.
As for performance, the impact is so small as to be non-existent, there are many, many other things that can have a real impact on performance, such as the structure and number of database queries, caching objects when looping instead of creating new instance etc. that will have a much greater impact.
Personally I prefer using the Ternary operators when checking for values that are not set and setting defaults. Consider this example
if( isset( $_POST['date'] ){
$date = $_POST['date'];
}else{
$date = date('Y-m-d');
}
Instead using Ternary
$date = ( isset( $_POST['date'] ) ? $_POST['date'] : date('Y-m-d');
The Ternary is much cleaner IMO, but its really a matter of personal preference.
Upvotes: 0
Reputation: 11607
To be TERNARY you cannot use the shortcut ?:
which collapses the meaning with the logical or
operator as shown by you.
So a real ternary operator would be:
$r = this() ? other() : that();
Now you cannot express this with the simple or
operator, which happens to be a special case of the ternary operator:
$r = this() ? this() : that(); // := this() or that()
Other than that, there is no difference at all but readability, which is more important than tiny questionable optimizations.
Upvotes: 0
Reputation: 96266
The second one has a boolean result. There's no restriction on the first one.
If you need a boolean value, use the logical operators.
As code clarify comes first, and this is micro-optimisation territory, just ignore the performance difference (if there's any).
Upvotes: 2