0

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?

michiman
  • 35
  • 7
  • 1
    To help you understand the null coalescing operator: https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator – Script47 Aug 19 '17 at 22:50
  • Possible duplicate of [PHP ternary operator vs null coalescing operator](https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator) – Script47 Aug 19 '17 at 22:52

1 Answers1

1

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).

Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30
  • isset() can't be null and return true. See http://php.net/manual/en/function.isset.php – rndus2r Aug 19 '17 at 23:18
  • But i get this error: "Undefined index: email". Any ideas why? – michiman Aug 19 '17 at 23:29
  • @michiman are you using `??` **inside** the parenthesis of `htmlspecialchars()`? Note that I do it inside of them. – Alejandro Iván Aug 19 '17 at 23:34
  • @AlejandroIván thats so nice! Thank you very much! – michiman Aug 19 '17 at 23:38
  • @AlejandroIván isset() and defined are two different things. isset() will return false even you assign null to a variable. You're mixing that up with empty(). empty() equals your definition of defined. See this example: http://sandbox.onlinephpfunctions.com/code/c413ea1da71a3815b97069b75198331c884a4d5b – rndus2r Aug 20 '17 at 01:14