PHP中||与\&\&优先级小对比

这篇博客探讨了PHP中逻辑运算符||与&&的优先级问题。通过实例代码解释了运算过程,强调了括号在确定运算顺序中的重要性,并展示了不同条件下if语句的执行逻辑。

今天在工作中看了一下同事代码,大概是这个样子:

if(($name == 'tancy' || $email == 'test@163.com') && $age == '24'){......}

写法和程序都没有问题,但是我突然勾起了我的探究心理,虽然不是特别重要的问题,但是还是研究了一下,所以来分享一下过程:

以以下代码为基础:

 

<?php
$name = 'tancy';

$email = 'test@163.com';

$age = '24';

if($name == 'tancy' || $email == 'test@163.com' && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>


按照上面情况页面肯定输出:true,我们都知道,在php中||的优先级比&&高,所以我们可以探索一下上面语法的执行过程:

当函数执行到if语句时,根据优先级的关系,所以会先执行$email == 'test@163.com' && $age == '24'语句,根据上面变量的赋值关系,这时会返回true,然后会执行$name == 'tancy' || true,当然肯定返回的是true,那么最终的输出结果是true。

然后我们先把$name的值改成错误的,比如:if($name == 'tom' || $email == 'test@163.com' && $age == '24'){......},那执行过程就是先执行$email == 'test@163.com' && $age == '24',返回值true,然后$name == 'tom' || true,这时无论$name == 'tom'是否正确,返回值肯定为true

<?php
$name = 'tancy';

$email = 'test@163.com';

$age = '24';

if($name == 'tom' || $email == 'test@163.com' && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>

2.然后我们把if语句中的优先级给他变换一下(加括号),像这样:if(($name == 'tancy' || $email == 'test@163.com') && $age == '24'){......},那么返回结果还是true,执行过程:

虽然&&的优先级比||高,但是括号的更高,所以先执行括号里面的内容($name == 'tancy' || $email == 'test@163.com'),当然返回结果肯定是true,再执行true && $age == '24',最终结果肯定是ture

<?php
$name = 'tancy';

$email = 'test@163.com';

$age = '24';

if(($name == 'tancy' || $email == 'test@163.com') && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>

3.最后我们把$name的值改成错误的,比如:if(($name == 'tom' || $email == 'test@163.com') && $age == '24'){......},那执行过程就是先执行$name == 'tom' || $email == 'test@163.com',返回值true,然后true && $age == '24',这时无论$name == 'tom'是否正确,返回值肯定为true

<?php
$name = 'tancy';

$email = 'test@163.com';

$age = '24';

if(($name == 'tom' || $email == 'test@163.com') && $age == '24'){
    echo 'true';
}else{
    echo 'error';
}
?>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值