简体   繁体   English

不同数据类型之间的php逻辑运算符“或”

[英]php logical operator 'or' between different data types

<?php

 $sample = (False or 436);
 echo $sample;
?>

I tried this code to identify and have and idea about how operator precedence effects to code. 我尝试使用此代码来识别并了解操作符优先级对代码的影响。 But I'm totally confusing with the answers I got. 但是我对得到的答案感到困惑。

 <?php

 $sample = (False or 436);
 echo $sample;
?>

gives answer as 1 给出答案为1

<?php

 $sample = (True or 436);
 echo $sample;
?>

gives 1 too 也给1

 <?php

 $sample = False or 436;
 echo $sample;
?>

gives nothing. 什么也没给。

As I could see whatever I put next to the or the answer was 1 如我所见,我旁边放的是or答案是1

PS I tried them on http://sandbox.onlinephpfunctions.com/ this online editor. PS我在http://sandbox.onlinephpfunctions.com/这个在线编辑器上尝试过它们。

I need to know the is the actual concept behind it. 我需要知道背后的实际概念。

The reason behind this is something called operator precedence. 其背后的原因是所谓的运算符优先级。 If you remove the brackets, the assignment $sample = false takes precedence before the or 436 function. 如果删除括号,则赋值$sample = false优先于or 436函数。 The result is echo false , which outputs nothing. 结果为echo false ,不输出任何内容。 That is why you in most cases should use || 因此,在大多数情况下,您应该使用|| operator instead. 运算符。

More information: http://php.net/manual/en/language.operators.precedence.php 更多信息: http : //php.net/manual/en/language.operators.precedence.php

You may want to have a read at PHP Type Comparison Tables as well as the Booleans documentation . 您可能需要阅读PHP类型比较表以及布尔文档 Pay special attention to Fred Koschara's notes in the top comment, which explains that the OR operator has lower precedence than the assignment operator. 请特别注意Fred Koschara在顶部注释中的注释,该注释说明OR运算符的优先级低于赋值运算符。 You may instead be looking to use || 您可能正在寻找使用||。 instead of OR, as the || 代替OR,例如|| operator does the same thing, but with higher precedence. 运算符执行相同的操作,但优先级更高。

As all the answers I got I could find all in one answer for what I posted. 作为我得到的所有答案,我可以在发布的内容中找到所有答案。 I think this may be helpful. 我认为这可能会有所帮助。

 <?php 
  $var1 = TRUE; 
  $var2 = FALSE; 
  $var3 = 123;


  $x = (int)$var2 or $var3;
  echo $x;// $x assigned to $var2 and type cast into int-display 0

  $y = ($var2 or $var3);
  echo $y;//operation inside the () returns true. so it prints 1

  $n = ($var2 or $var2);
  echo $n;//operation inside the () returns false.It concider as NULL. display nothing
  echo (int)$n;//print numerical value for false-0

  $z = $var2;
  echo $z;//returns 0. It is considered as NULL. so display nothing

 ?>

This is the exact answer I really expected. 这是我真正期望的确切答案。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM