redpip redpip - 22 days ago 6
PHP Question

PHP non-falsy null coalesce operator

i was very happy when i found out about php7's null coalesce operator. But now, in practice, I see that it's not what i thought it is:

$x = '';
$y = $x ?? 'something'; // assigns '' to $y, not 'something'


I want something like either C#'s
??
operator or python's
or
operator:

x = ''
y = x or 'something' # assings 'something' to y


Is there any short-hand equivalent for this in php?

Answer

No, there's no non-falsy null coalesce operator for PHP, but there's a workaround. Meet ??0?: :

<?php

$truly = true; // anything truly
$false = false; // anything falsy (false, null, 0, '0', '', empty array...)
$nully = null;

// PHP 7's "null coalesce operator":
$result = $truly ?? 'default'; // value of $truly
$result = $falsy ?? 'default'; // value of $falsy
$result = $nully ?? 'default'; // 'default'
$result = $undef ?? 'default'; // 'default'

// but because that is so 2015's...:
$result = !empty($foo) ? $foo : 'default';

// ... here comes...
// ... the "not falsy coalesce" operator!
$result = $truly ??0?: 'default'; // value of $truly
$result = $falsy ??0?: 'default'; // 'default'
$result = $nully ??0?: 'default'; // 'default'
$result = $undef ??0?: 'default'; // 'default'

// explanation:
($foo ?? <somethingfalsy>) ?: 'default';
($foo if set, else <somethingfalsy>) ? ($foo if truly) : ($foo if falsy, or <somethingfalsy>);

// here is a more readable[1][2] variant:
??''?:

// [1] maybe
// [2] also, note there is a +20% storage requirement

Source:
https://gist.github.com/vlakoff/890449b0b2bbe4a1f431