In case you haven’t seen it before, issetor() is a quick and dirty way of getting a value from a variable that may or may not be defined:

function issetor(&$var, $default=NULL) {
  return isset($var) ? $var : $default;

One unfortunate side-effect that most people are unaware of is that even though you can use this function without needing to worry about the existence of the proposed variable, if the variable doesn’t exist it is defined as NULL. Therefore the following type of strange case could occur:

$arr = [1,2,3];
echo count($arr); // 3
$fourth = issetor($arr[4]);
echo count($arr); // 4

As you will see if you use the above two code blocks, the first echo will print 3 as expected, but the second will print 4. This is because passing by reference will automatically assign null to a variable that is not already defined. Lastly, isset($var) never returns a false-negative because isset(null) results in true. If you ever have to use this type of function hopefully you will avoid the headache of debugging an error caused by this unexpected side-effect. šŸ˜Ž

Categories: BlogPHP

1 Comment

Benjamin Kuz · October 24, 2016 at 4:41 PM

This is better:

function coalesce(&...$args) {
foreach ($args as $arg) {
if (isset($arg)) return $arg;
return null;

Doing it like this will just return the first value that is set and you can pass it as many arguments as you like. All you do is make your default the last argument.

Leave a Reply

Your email address will not be published. Required fields are marked *