1

In javascript, you can do...

var this_is_null = null;
var this_is_real = 'Hello';

var result = this_is_null || this_is_real;

alert(result); 

Resulting popup:

Hello

Now, I'm trying to do similar in PHP, with something like

$this_is_null = null;
$this_is_real = "Hello";

$result = $this_is_null or $this_is_real;
$result2 = $this_is_null || $this_is_real;

PRINT($result2);
PRINT($result);

However, this results in

1

So, is there an equivalent in PHP to or-based variable assignment?

http://viper-7.com/57VRKQ

lilHar
  • 1,735
  • 3
  • 21
  • 35

2 Answers2

3

Even shorter:

$result = $this_is_null ?: $this_is_real;

For reference, see http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary.

localheinz
  • 9,179
  • 2
  • 33
  • 44
  • Has the same issues as lanis's answer... very good answer, works for the example case in the question, but doesn't quite hit feature parity with the || variable assignment because it doesn't work if the variable hasn't been declared (one common use for the || in variable declaration in javascript). For example: `$thing = array(); $thing[0] = "real"; $result2 = $thing[1] ? $thing[1]: $thing[0] ;` would give an error. I'm thinking of using isset in there, but then it wouldn't check if it's not null. – lilHar Dec 31 '15 at 01:36
1

You can do this instead :

$result2 = $this_is_null ? $this_is_null : $this_is_real ;
Ianis
  • 1,165
  • 6
  • 12
  • Very similar to the || in variable declaration, although I'm trying to few test cases and noticing it's different in the case if you're assigning from an index. For example: `$thing = array(); $thing[0] = "real"; $result2 = $thing[1] ? $thing[1]: $thing[0] ;` – lilHar Dec 31 '15 at 01:34