drau67562 2015-11-20 09:51
浏览 5
已采纳

|之间的区别 和|| 在PHP中[重复]

This question already has an answer here:

I have simple code

$value = 5;
$string = 'Abc';

var_dump(($value > 0) || (strlen($string) == 2));
var_dump(($value > 0) | (strlen($string) == 2));

Only what is changed is type of returned value (first is boolean, second int). There is another difference between | and ||? Can I change one to another?

Live test: http://sandbox.onlinephpfunctions.com/code/548ab723cbd156be70a596978427fbd73ce4639f

</div>
  • 写回答

1条回答 默认 最新

  • douchengjue9892 2015-11-20 09:53
    关注

    var_dump(($value > 0) || (strlen($string) == 2));

    || is a logical logical operatpor, see http://php.net/manual/de/language.operators.logical.php

    var_dump(($value > 0) | (strlen($string) == 2));

    | is a bitwise operator, see http://php.net/manual/de/language.operators.bitwise.php

    Sure, you can change | to ||, but you won't get the same result ;) A little explanation for your code, but you should really read the doc for bit- and logical operators:

    You already answered, that both don't do the same:

    var_dump(($value < 0) || (strlen($string) == 2)); -> returns a boolean true

    var_dump(($value < 0) | (strlen($string) == 2)); -> returns an integer 1

    If you do:

    var_dump(true === 1);
    

    You will get false, because integer 1 isn't a boolean true, even if:

    var_dump(true == 1);
    

    or

    var_dump(true === (bool)1);
    

    will return true (== doesn't check for type, see the docs, and (bool) casts the integer 1 to be a boolean true (see http://php.net/manual/de/language.types.boolean.php#language.types.boolean.casting to know what is false and what is true).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并