Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ternary statement using 'and'

Tags:

php

Ok so I just realized some wierd behavior with PHP and would like to know why this happens. So running this code:

 var_dump( true and false ? 'one' : 'two' );

Outputs

boolean true

instead of 'two' as you would expect... The problem appears to be using 'and'.

Running:

var_dump( true && false ? 'one' : 'two' );

outputs

string 'two' (length=3)

just as expected. Why does using 'and' instead of '&&' cause this weird behavior? Are they not supposed to be the same?

like image 253
Zaptree Avatar asked Apr 22 '12 22:04

Zaptree


People also ask

How use ternary operator in if condition in PHP?

It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);

Does PHP support ternary operator?

The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

Is ternary operator faster than if in PHP?

So, why does the ternary operator become so slow under some circumstances? Why does it depend on the value stored in the tested variable? The answer is really simple: the ternary operator always copies the value whereas the if statement does not. Why?

Is null ternary operator PHP?

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.


2 Answers

That's because ?: has higher precedence than and, but lower than &&.

like image 77
rid Avatar answered Sep 16 '22 20:09

rid


It's because and have lower priority than && and ?:.

like image 20
Pavel Strakhov Avatar answered Sep 16 '22 20:09

Pavel Strakhov