This:

echo (isset($foo) && $foo) ? $foo : 'default';

Is equivalent to:

echo $foo ?: 'default';

Please don't endorse usage of undefined variables.

On 17 Jan 2018 19:00, "Lito" <i...@eordes.com> wrote:

> Related with Request #75833 https://bugs.php.net/bug.php?id=75833
>
> From PHP 7 null-coalescing operator is a great option to avoid a previous
> exists check with isset.
>
> But I think that this comaparison can be improved adding a ternary
> operator like ??: and check also empty values.
>
> Example:
>
> --------------------------------------
>
> <?php
>
> $foo = '';
>
> // Current response with ternary operator
>
> echo $foo ?: 'default'; // 'defaut'
>
> // Current response with null-coalescing operator
>
> echo $foo ?? 'default'; // ''
>
> // Possible response with ternary null-coalescing operator
>
> echo $foo ??: 'default'; // 'defaut'
>
> // Same response with current PHP available code
>
> echo (isset($foo) && $foo) ? $foo : 'default'; // 'default'
>
> /** ------------------------------- **/
>
> $foo = false;
>
> // Current response with ternary operator
>
> echo $foo ?: 'default'; // 'defaut'
>
> // Current response with null-coalescing operator
>
> echo $foo ?? 'default'; // false
>
> // Possible response with ternary null-coalescing operator
>
> echo $foo ??: 'default'; // 'defaut'
>
> // Same response with current PHP available code
>
> echo (isset($foo) && $foo) ? $foo : 'default'; // 'default'
>
> /** ------------------------------- **/
>
> $foo = null;
>
> // Current response with ternary operator
>
> echo $foo ?: 'default'; // 'defaut'
>
> // Current response with null-coalescing operator
>
> echo $foo ?? 'default'; // 'defaut'
>
> // Possible response with ternary null-coalescing operator
>
> echo $foo ??: 'default'; // 'defaut'
>
> // Same response with current PHP available code
>
> echo (isset($foo) && $foo) ? $foo : 'default'; // 'default'
>
> /** ------------------------------- **/
>
> unset($foo);
>
> // Current response with ternary operator
>
> echo $foo ?: 'default'; // PHP Notice:  Undefined variable: foo
>
> // Current response with null-coalescing operator
>
> echo $foo ?? 'default'; // 'defaut'
>
> // Possible response with ternary null-coalescing operator
>
> echo $foo ??: 'default'; // 'defaut'
>
> // Same response with current PHP available code
>
> echo (isset($foo) && $foo) ? $foo : 'default'; // 'default'
>
> --------------------------------------
>
> What about?
>
> Thanks!
> Lito.
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

Reply via email to