Last active
April 8, 2020 11:35
-
-
Save timotheemoulin/f6d833ffb49a266a586982f9d0f0a4ae to your computer and use it in GitHub Desktop.
Check what really does the coalesce operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// undefined variable | |
echo "?? prints 'default'"; | |
echo "<br>"; | |
var_dump($a ?? 'default'); | |
echo "<br><br>"; | |
echo "?: sends a notice 'undefined variable' and prints 'default'"; | |
echo "<br>"; | |
var_dump($a ?: 'default'); | |
echo "<br><br>"; | |
// empty value | |
$empty = ''; | |
echo "?? allows a empty string"; | |
echo "<br>"; | |
var_dump($empty ?? 'default'); | |
echo "<br><br>"; | |
echo "?: doesn't"; | |
echo "<br>"; | |
var_dump($empty ?: 'default'); | |
echo "<br><br>"; | |
// false value | |
$empty = false; | |
echo "?? allows a false value"; | |
echo "<br>"; | |
var_dump($empty ?? 'default'); | |
echo "<br><br>"; | |
echo "?: doesn't"; | |
echo "<br>"; | |
var_dump($empty ?: 'default'); | |
echo "<br><br>"; | |
// null value | |
$empty = null; | |
echo "?? doesn't allow a null value"; | |
echo "<br>"; | |
var_dump($empty ?? 'default'); | |
echo "<br><br>"; | |
echo "?: neither"; | |
echo "<br>"; | |
var_dump($empty ?: 'default'); | |
echo "<br><br>"; | |
// missing array index | |
$array = ['foo' => 'foo']; | |
echo "?? allows missing array index"; | |
echo "<br>"; | |
var_dump($array['bar'] ?? 'default'); | |
echo "<br><br>"; | |
echo "?: doesn't and prints a notice"; | |
echo "<br>"; | |
var_dump($array['bar'] ?: 'default'); | |
echo "<br><br>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result of the execution is