这个 PHP if 循环应该是这里最奇怪的问题,但我确实想知道


This PHP if loop should be the most, strangest question here, but I do want to know

当 $cnt=3 和 $cnt=3 以外的另一个循环时执行第一个循环。 无论$cnt的值是多少,无论 $cnt=3 还是 $cnt==3,都只执行第一个循环。

$ary = explode(".", $string);
$cnt = count($ary);
if ($cnt="3") {
//executes when cnt=3
  $fnm = $d[0];
  $fnxt = $d[1].".".$d[2];
} else {
//executes when anything other than when cnt=3
   $fnm = $d[0];
   $fnxt = $d[1];
}

我可能在这里错过了一些东西,这里到底出了什么问题?

谢谢珍

您在比较中缺少一个=符号。 它应该是:

if ($cnt == 3)

实际上,您将 3 分配给 $cnt ,并且由于赋值运算符返回其值,因此测试变为 if (3) ,当然总是成功的。

注意:count()返回一个整数,这就是为什么我上面的版本与3进行比较而不是"3"

您缺少"="

if ($cnt="3") {  // This is an assignment, which returns true.

这应该是:

if ($cnt == "3") { // This is a comparison.
$cnt="3"

"3"分配给$cnt,表达式作为一个整体计算为"3",这是真的,这会导致if块始终被执行。 为了测试$cnt是否等于"3",请使用==运算符:$cnt == "3"