简体   繁体   English

如何检查是否设置了变量?

[英]How to check if any variables are set?

checking if all are set 检查是否全部设置

if(
    isset($var1) &&
    isset($var2) &&
    isset($var3)
){}

can be re-written as 可以重写为

if(isset($var1,$var2,$var3)){}

but what's the syntax for if any are set? 但什么是对,如果任何设置的语法?

if(
    isset($var1) ||
    isset($var2) ||
    isset($var3)
){}

Looks ugly; 看起来很丑; is there any better way to write this? 有什么更好的方法可以写这个吗?

You have to pass strings instead of the variables, but for fun: 您必须传递字符串而不是变量,但这很有趣:

if(compact('var1', 'var2', 'var3')) {
    echo 'one or more is set';
} else {
    echo 'none are set';
}

I guess one could write a simple function to use, but there's probably a cleaner way. 我想可以编写一个简单的函数来使用,但是可能有一种更简洁的方法。

function anyset(...$vars){
    foreach($vars as $var){
        if(isset($var)){
            return true;
        }
    }
    return false;
}

if(anyset($var1,$var2,$var3)){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM