Search code examples
phpnull-coalescing-operator

Using null coalescing operator to echo an escaped output


is there a possiblity to use the null coalescing operator AND echo in one expression like this:

echo htmlspecialchars($_POST['email']) ?? '';

As a short form of

if (isset($_POST['email'])) {
  echo htmlspechars($_POST['email']);
}

Any ideas?


Solution

  • The null coalescing operator won't emit a E_NOTICE when a parameter isn't defined.

    So you could do $email = htmlspecialchars($_POST['email'] ?? '');

    Note that the null coalescing operator is applied to the variable ($_POST['email']) and not to the result of htmlspecialchars().

    If you wanted to use conditional ternary operator (?:), then you should have to check if the variable is set before operating on it.

    if ( isset($_POST['email']) ) {
        $email = htmlspecialchars($_POST['email'] ?: '');
    }
    

    Note that isset() will be TRUE if the variable is set (or, in other words, it is defined and has a value different than NULL).