我不明白为什么这会发生空的PHP变量

I try to do this:

if ($var !== ""){
    $message = "whatever";
}

But end up having to do this:

if ($var == ""){
    //do nothing
} else {
    $message = "whatever";
}

Why does that happen? Shouldn't both of those mean the same thing?

!= and == are opposites (non-strict comparison operators).

!== and === are opposites (strict comparison operators, where the value must match what you are comparing exactly).

If you use != instead of !==, your code should work. But:

  • You should understand what the actual value of your variable is - it's not an empty string. You can use print_r( $var ); to see it.
  • It's better to use the strict comparison operators === and !==, because they have well-defined behavior that is easier to remember and debug.

$var could be != '' but not= '' eg .. null

  if ($var == ""){
   //do nothing
 } else {
   if (is_null($var) {
     $message ='NULL';
   } else {
     $message = "whatever";
   }

}

As $var is really string just use:

if ($var){//any non-empty string will work fine as it will be casted to boolean automatically
    $message = "whatever";
}