有谁知道为什么 PHP 中的 for
循环不能按预期工作?请检查以下内容:
检查了有关运算符的文档和谷歌:http://php.net/manual/en/language.operators.increment.php
<?php
$a = "Z";
$b = "AL";
echo $a."<br>".$b."<br>";
for ($x = $a; $x <= $b; $x++) {
echo "The number is: $x <br>";
}
while(true){
if($a == $b)break;
echo $a."<br>";
$a++;
}
?>
for
循环不进行迭代,而 while
循环则进行迭代。预期输出应从 Z
-AL
迭代,while
循环正在执行此操作,但 for
循环则不是迭代。
for
循环应该遵循 Perl 的迭代 ( http://php.net/manual/en/language.operators.increment.php ),但显然表示 AL
不大于 Z
。
但是,当将这些字母转换为数值时,for
循环将像处理整数一样工作。
最佳答案
您的循环未迭代,因为条件失败 - 'Z' 大于 'AL'。您可以使用 strnatcmp()
来完成您想要的操作:
for ($x = $a; strnatcmp($x, $b); $x++) {
echo "The number is: $x\n";
}
输出:
The number is: Z
The number is: AA
The number is: AB
The number is: AC
The number is: AD
The number is: AE
The number is: AF
The number is: AG
The number is: AH
The number is: AI
The number is: AJ
The number is: AK
[编辑]实际上,呃,这甚至没有必要,只需检查不相等即可:
for ($x = $a; $x !== $b; $x++) {
请注意,这可能会给您带来一个相差一的错误,具体取决于您想要的输出是什么。如果您想要再进行一次迭代,只需在循环之前添加 $b 即可,或者像您的示例中那样使用 while 循环。
关于PHP FOR迭代不迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54114963/