使用 '!' 时 PHP 中的意外输出


unexpected output in php while using `!`

我只是在尝试一个小程序,但我得到了意想不到的输出。

for($i=20;!$i<20;$i--)
echo '*';

预期输出仅*$i=20为 false 时的第一种情况,因此!$i<20应返回 true,但循环执行的次数等于 $i 的值。

我尝试操作值,并得出结论,当我将值设置为负数时$i,循环变得无限。

进一步我试过这个

echo 20<20;

输出与预期不符然后

echo !20<20;

输出按预期1

现在,当它尝试时:

19<20

它返回 1 但当我尝试时

!19<20

它正在返回1为什么会这样??我在WAMP服务器上运行PHP,我的PHP版本5.5.0

注意:我对 for 循环没有任何问题,我可以处理它,所以请不要回答纠正我的循环,而是我对!的工作感到困惑,所以请回答它。

你需要括号来"不"正确的部分:

for($i=20;!($i<20);$i--)
  echo '*';

!20<20的示例是这样做的:

!20<20
!(true)<20  <- converts the type to bool so we can negate
false<20    <- negates the true to false
0<20        <- converts the false to an int to compare
true

!19<20的例子是这样做的:

!19<20
!(true)<20  <- converts the type to bool so we can negate
false<20    <- negates the true to false
0<20        <- converts the false to an int to compare
true

试试

for($i=20;!($i<20);$i--)
echo '*';

问题是"!$i"首先执行,然后"<"操作员工作。