-2

I want to insert NULL in a table with the null coalescing operator ( > php 7) I always get and empty string from my POST variables and I did this :

$phone = !empty($this->$_POST['phone']) ?? "NULL";

But when I dump the result of $phone, it's always false...

Thank you

Anisur Rahman
  • 644
  • 1
  • 4
  • 17
Tnecniv
  • 27
  • 6
  • 2
    "The null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand." - the return value of `empty` is always a boolean, so even after you negate it, it is still a boolean - and that very much "exists." – CBroe Mar 07 '22 at 09:05
  • 2
    If you want to use `NULL` as the content, why not use that instead of a string with the content `NULL`? – Nico Haase Mar 07 '22 at 09:09

2 Answers2

0

Just use $phone = $this->$_POST['phone'] ?? "NULL";
You are getting false because of empty() returns boolean.

Anisur Rahman
  • 644
  • 1
  • 4
  • 17
0

Keep in mind that there is a difference between "NULL" and NULL in SQL (and almost everywhere else).

I don't think the null coalescing operator does what you want it to do. It only works if you're starting with a null value, not if you want to turn a falsy value into null.

You could do $phone = !empty($this->$_POST['phone']) ? $this->$_POST['phone'] : null;, or probably just $phone = $this->$_POST['phone']) ?: null;

Arthur Boucher
  • 307
  • 1
  • 7