[英]If-Else loop output
<?php
$x = 1;
if ($x == 2)
print "hi" ;
else if($x = 2)
print $x;
else
print "how are u";
?>
Apologies for this basic question as I am a beginner at php.为这个基本问题道歉,因为我是 php 的初学者。
I was expecting the else statement to be executed and print "how are u", but it executed the elseif statement and printed '2' instead.我期待执行 else 语句并打印“你好吗”,但它执行了 elseif 语句并打印了“2”。 May I ask why does $x become assigned to 2?请问为什么 $x 被分配给 2 ? Thanks in advance.提前致谢。
You are SETTING x=2
in your else if
--> else if($x = 2)
-- This would be more appropriate.. Check for absolute ===
.. Then check for truthy ==
.. IE您在else if
--> else if($x = 2)
中设置x=2
-- 这会更合适.. 检查绝对===
.. 然后检查真值==
.. IE
<?php
$x = 1;
if ($x === 2)
print "hi" ;
else if($x == 2)
print $x;
else
print "how are u";
?>
Conversely.. You can play with truthy vs absolute by comparing an integer to string too.. Like:相反..您也可以通过将 integer 与字符串进行比较来玩真值与绝对值.. 喜欢:
<?php
$x = 2;
if ($x === 2) // Will return true
print "Is absolute integer" ;
else if($x == 2) // Will return true
print "Is truthy integer";
else if($x === '2') // Will return false
print "Is absolute string";
else if($x == '2') // Will return true
print "Is truthy string";
else
print "how are u";
?>
Which will never reach the else.. But you can see how operators can make or break a program..哪个永远不会到达 else .. 但是您可以看到操作员如何制作或破坏程序..
<?php $x = 1; if ($x == 2) print "hi" ; else if($x = 2) /* you assign $x 2 and it's true */ print $x; else print "how are u"; ?>
In the elseif you are asigning the number 2 to $x which will always return true.在 elseif 中,您将数字 2 分配给 $x,这将始终返回 true。 Because of that it will never go to the else block.因此,它永远不会 go 到 else 块。 Dont use = when doing comparisons but == or ===.在进行比较时不要使用 =,而是使用 == 或 ===。
<?php
$x = 1;
if ($x == 2)
print "hi" ;
else if($x == 2)
print $x;
else
print "how are u";
?>
this is the right way to do it.这是正确的方法。 Also it doesnt make sense to check both in if and elseif that $x == 2 since it will never execute the elseif block.此外,检查 if 和 elseif that $x == 2 也是没有意义的,因为它永远不会执行 elseif 块。 Let me try to explain it better, if you do:如果您这样做,让我尝试更好地解释它:
if ($x = 2)
thats will assign 2 to $x and this is then the same as:那就是将 2 分配给 $x ,这与以下内容相同:
if ($x)
since the $x now holds the number 2 this is also the same as:因为 $x 现在持有数字 2 这也与:
if (2)
this is always true so it will never go to further checks no matter what the number is.这总是正确的,因此无论数字是多少,它都不会进一步检查 go。
This is because =
is assignment operator not comparison like ==
.这是因为=
是赋值运算符而不是像==
这样的比较。 That is why $x
is assigned value 2 and the else if condition is met and executed.这就是为什么$x
被赋值为 2 并且 else if 条件被满足并被执行的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.