Skip to content

Instantly share code, notes, and snippets.

@timotheemoulin
Last active April 8, 2020 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timotheemoulin/f6d833ffb49a266a586982f9d0f0a4ae to your computer and use it in GitHub Desktop.
Save timotheemoulin/f6d833ffb49a266a586982f9d0f0a4ae to your computer and use it in GitHub Desktop.
Check what really does the coalesce operator
<?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>";
@timotheemoulin
Copy link
Author

timotheemoulin commented Apr 8, 2020

The result of the execution is

?? prints 'default'
string(7) "default"

?: sends a notice 'undefined variable' and prints 'default'

NOTICE Undefined variable: a on line number 12
string(7) "default"

?? allows a empty string
string(0) ""

?: doesn't
string(7) "default"

?? allows a false value
bool(false)

?: doesn't
string(7) "default"

?? doesn't allow a null value
string(7) "default"

?: neither
string(7) "default"

?? missing array index
string(7) "default"

?: missing array index

NOTICE Undefined index: bar on line number 60
string(7) "default"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment