Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active March 18, 2016 15:28
Show Gist options
  • Save lsloan/0dcb620668f1e16fba33 to your computer and use it in GitHub Desktop.
Save lsloan/0dcb620668f1e16fba33 to your computer and use it in GitHub Desktop.
PHP default values for unset variables

In PHP, I wanted to do something like $myArray->get('key', 'default'), but that doesn't work in PHP for a number of reasons. (Namely, arrays aren't objects and there isn't a get() function for arrays.) I found it worked with @$myArray['key'] || false, but only because I was using a Boolean value, like false. The || operator always causes the interpreter to treat expressions on each side of it as Booleans. If I tried a different default value, like @$myArray['key'] || 'default', it didn't work as I expected, because it treats 'default' as a Boolean true.

However, since version 5.3, PHP's ternary operator allows an empty "then" result, which returns the initial condition if it's true, otherwise, it returns the required "else" result. The following code illustrates the difference between using || and ?:.

Update: I've noticed that if the initial value used with ?: is an empty, non-null string (i.e. ''), this breaks down. It's being converted to a Boolean false, apparently.

<?php
/*
* Run this at: https://repl.it/BxaW
*/
function counter() {
global $_;
return (@$_++ ? $_ : $_) . ': '; // just for fun
}
echo counter() . (((@$foo['bar'] || 'baz') === 'baz') ? 'true' : 'false') . PHP_EOL; // 1: false
echo counter() . (((@$foo['bar'] ?: 'baz') === 'baz') ? 'true' : 'false') . PHP_EOL; // 2: true
echo counter() . (@$foo['bar'] || 'baz') . PHP_EOL; // 3: 1
echo counter() . (@$foo['bar'] ?: 'baz') . PHP_EOL; // 4: baz
$foo['bar'] = 'qux';
echo counter() . (@$foo['bar'] || 'baz') . PHP_EOL; // 5: 1
echo counter() . (@$foo['bar'] ?: 'baz') . PHP_EOL; // 6: qux
$foo['bar'] = strval('');
echo counter() . var_export($foo, true) . PHP_EOL; // 7: array ('bar' => '',)
echo counter() . (@$foo['bar'] || 'baz') . PHP_EOL; // 8: 1
echo counter() . (@$foo['bar'] ?: 'baz') . PHP_EOL; // 9: baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment