Check if atleast of the variables have a value in

2019-08-31 03:33发布

问题:

I have two variables in php/magento as in below

$currentA = $advert->getA();
$currentB = $advert->getB();

I want to make sure that atleast one of these have a value....Basically a validation to make sure atleast one of these have a value. Am I doing it correct?

   $currentA = $advert->getA();
   $currentB = $advert->getB();
   if (!($currentA != '' || $currentB !== '')) {
           echo "do something";
   }

回答1:

It is more complicated than that. Like SQL fields, php variables may also be NULL and generate warning when accessed for data.

So use empty(var) because that tests for all of the possible empty conditions and doesn't give warnings if the variable has been declared without a value.

   if (!(empty($currentA) || empty($currentB))) {
           echo "do something";
   }

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float) "
  • 0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)


回答2:

You wouldn't need the ! because if either of these have a value, it will return true, and the ! operator checks if this condition is false, so it will work opposite of when it's supposed to. You should try

if ($currentA || $currentB) {
       echo "do something";
}


标签: php magento