异或运算符(xor) 的妙用

id值
时间值
 
  

 

我要实现的功能是当中 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);
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值