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.
isset()is the usual way of doing this:Note: you can assign
nullto a variable and it will be assigned. This will yield different results withisset()andis_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:is equivalent to:
You can do the second form in PHP but PHP has some funky rules about type juggling. See Converting to boolean:
So after:
$a would equal 5. Likewise:
You have to watch out for these things.