我要实现的功能是当中 id值或是时间值对应的文本框中有一个为空时就报错,但可以全为空
一般的做法是:
<?php
$id = $_POST['id'];
$t = $_POST['time'];
//传统上我会这么做
//先判断全不为空
if(!empty($t) or !empty($id)) {
//判断当中有一个为空时
if( empty($t) or !empty($id)) {
die( "Search conditions are empty or not empty at the same time");
}
if( !empty($t) or empty($id)) {
die( "Search conditions are empty or not empty at the same time");
}
}
?>
但如果用xor来实现只需要一段代码即可
<?php
$id = $_POST['id'];
$t = $_POST['time'];
//意思为当提交的两个表单当中有一个为空时就报错但允许全为空
if( empty($t) xor empty($id))
{
die( "Search conditions are empty or not empty at the same time");
}
?>
不过如果能用三元运算符就更牛了,只要一句就可以了:
<?php
$id = $_POST['id'];
$t = $_POST['time'];
//意思为当提交的两个表单当中有一个为空时就报错但允许全为空
die(( empty($t) xor empty($id))? "Search conditions are empty or not empty at the same time":false);
?>