检查变量中的至少一个在php中是否有值 [英] Check if atleast of the variables have a value in php

查看:37
本文介绍了检查变量中的至少一个在php中是否有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php/magento中有两个变量,如下所示:

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";
   }

推荐答案

这要复杂得多.像SQL字段一样,php变量也可能为NULL,并且在访问数据时会生成警告.

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

请使用 empty(var),因为这会测试所有可能的空条件,并且不会如果变量已声明为没有值,则发出警告.

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:

  • "(一个空字符串)
  • 0(0为整数)
  • 0.0(浮点数为0)"
  • 0(0作为字符串)
  • NULL
  • array()(一个空数组)
  • $ var;(已声明变量,但没有值)

这篇关于检查变量中的至少一个在php中是否有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆