Imran Ali
Imran Ali

Reputation: 13

Can logical operator be used with in ternary operators in PHP

Is this statement correct in PHP

$abc = $x === "" || $y !== $z ? "true" : "false";

Upvotes: 1

Views: 269

Answers (3)

Pavan Jiwnani
Pavan Jiwnani

Reputation: 274

I just tested it out and it works absolutely fine. You just need to add round brackets for the condition statement So your code will look like this

$abc = ($x === "" || $y !== $z) ? "true" : "false";
echo $abc;

Upvotes: 1

rvandoni
rvandoni

Reputation: 3397

yes. it works correctly.

$x = 1;
$y = 2;

$z = 100;

$abc = $x === "" || $y !== $z ? "true" : "false";

var_dump($abc); // true

and

$x = 1;
$y = 100;

$z = 100;

$abc = $x === "" || $y !== $z ? "true" : "false";

var_dump($abc); // false

but, please, use parenthesis!

$abc = ($x === "" || $y !== $z) ? "true" : "false";

Upvotes: 1

Shimul Chowdhury
Shimul Chowdhury

Reputation: 191

Why not. I believe it will work. Just put parenthesis. Like

$abc = ($x === "" || $y !== $z) ? "true" : "false";

Upvotes: 1

Related Questions