Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have an equivalent to the ||= operator?

Tags:

php

I'm wanting to assign a variable only it hasn't already been assigned. What's the PHP way of doing the following?

$result = null;
$result ||= check1();
$result ||= check2();
$result ||= "default";

I checked the standard operators and the is_null function, but there doesn't seem to be an easy way of doing the above operation.

like image 335
brianegge Avatar asked Jul 19 '09 08:07

brianegge


1 Answers

isset() is the usual way of doing this:

if (!isset($blah)) {
  $blah = 'foo';
}

Note: you can assign null to a variable and it will be assigned. This will yield different results with isset() and is_null() so you need to be clear on what you mean by "not assigned". See Null vs. isset(). This is also one case where you need to be careful about doing automatic type conversion, meaning using the !=/== or ===/!== depending on the desired result.

You can use boolean shorthand for this too (which is what the Perl ||= operator is). As of PHP 5.2.x there is no operator like you speak of. In Perl:

$a ||= $b;

is equivalent to:

$a = $a || $b;

You can do the second form in PHP but PHP has some funky rules about type juggling. See Converting to boolean:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

So after:

$a = 0;
$a = $a || 5;

$a would equal 5. Likewise:

$a = 0;
$b = '';
$c = $a == $b; // true
$d = $a === $b; // false

You have to watch out for these things.

like image 87
cletus Avatar answered Sep 23 '22 02:09

cletus