Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-将IF语句放入变量中_Php_Variables_If Statement - Fatal编程技术网

PHP-将IF语句放入变量中

PHP-将IF语句放入变量中,php,variables,if-statement,Php,Variables,If Statement,我想把一个if语句放入一个变量中,以减少代码行数。。。例如,我想这样做: $empty = if(empty($_POST['username']) && empty($_POST['password'])) if($empty){ // echo message; } elseif(!$empty){ ///echo message; } 这样的东西能生产出来吗?还是我把事情弄得太复杂了?只需省略if: $empty = empty($_POST['username'])

我想把一个if语句放入一个变量中,以减少代码行数。。。例如,我想这样做:

$empty = if(empty($_POST['username']) && empty($_POST['password']))
if($empty){ // echo message; 
}
elseif(!$empty){ ///echo message; 
}
这样的东西能生产出来吗?还是我把事情弄得太复杂了?

只需省略if:

$empty = empty($_POST['username']) && empty($_POST['password']);
试试这个

$empty = (empty($_POST['username']) && empty($_POST['password'])) ? 0 : 1;

if($empty){ // Not empty message here...; 

}
else{ ///Empty message here....; 

}
你可以用


三元运算符的使用:

echo empty($_POST['username']) && empty($_POST['password']) ? 'empty message' : 'Not empty message';

您可以直接使用
echo
和三值运算符,而不是获取
$empty
的值并将其打印出来。

否,三值运算符基本上是if/else的简写-将其视为(if)?真:假;
echo empty($_POST['username']) && empty($_POST['password']) ? 'empty message' : 'Not empty message';