-3

In javascript the logical or-operator returns the first truthy operand, e.g.

var x = null || 5 || 1;

assigns 5 to x.
Is there somthing similar for php?

VolkerK
  • 95,432
  • 20
  • 163
  • 226

2 Answers2

2

The use case you describe is: if the value exists use it, otherwise use a default value. This is a pretty common pattern.

As of PHP 5.3 you can do:

$var = $foo ?: 5;

In older versions you can do:

$var = $foo ? $foo : 5;

Note that in:

var x = null || 5 || 1;

the final path || 1 will never get chosen because 5 is never falsy.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

|| is a logical operator in PHP and many other programming languages. Learn more about logical operators in the official PHP documentation.

What you are searching for is a ternary operator, which is the following in PHP:

$valueOne = $null ? $null : $five;

Since PHP 5.3 you may use the short form:

$valueOne = $null ?: $five;

And since its associativity is left you may use it multiple times successively:

$valueOne = $null ?: $five ?: $one;
Daniel
  • 3,541
  • 3
  • 33
  • 46