2

Can I use the OR argument in this way in PHP? Meaning if $x is null assign $y to $var.

$var = $x || $y

Simple question, cheers!

wilsonpage
  • 17,341
  • 23
  • 103
  • 147

4 Answers4

8

No. PHP's boolean operators evaluate to true or false, not the value of the operands as in Javascript. So you'll have to write something like this:

$var = $x ? $x : $y;

Since 5.3, you can write this though, which basically has the same effect as Javascript's ||:

$var = $x ?: $y;

That requires that $x exists though, otherwise you should check with isset first.

deceze
  • 510,633
  • 85
  • 743
  • 889
3

No, in this way you assign a boolean to $var

$var = $x or $y;

means: $var is true, if $x or $y. You are looking for the ternary operator

$var = isset($x) ? $x : $y;
// or
$var = empty($x) ? $y : $x;

The ternary operator always works like

$var = $expressionToTest
     ? $valueIfExpressionTrue
     : $valueIfExpressionFalse

With PHP5.3 or later you can omit $valueIfExpressionTrue

$var = $expressionToTest ?: $valueIfExpressionFalse;
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
1
$x=0;
$y=9;
$var = ($x)?$x:$y;

echo $var;

if variable x is null then var will be 9,or else it will be value of x.

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
0

This question is already answered, but I juist wanted to point your attention to the other usage of OR and AND operators in PHP

defined('SOMETHING') OR define('SOMETHING', 1);

if this case if SOMETHING is not defined (defined('SOMETHONG') evaluates to false) expression after OR will be evaluated

$admin AND show_admin_controls();

if $admin is evaluated to boolean true, show_admin_controls() function will be called

I usually use it to check if some constant is defined, but I've seen a lot of examples of good-looking and really well-readable code using this constructions for other purposes.

Nemoden
  • 8,816
  • 6
  • 41
  • 65