PHP FOR迭代不迭代

标签 php perl for-loop

有谁知道为什么 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/

相关文章:

PHP Heroku 后台 worker ?

perl - 如何为 Perl 制作静态分析调用图?

regex - 如何对从 Perl 的菱形运算符返回的数据进行多行匹配

oracle - 查询结果在Oracle内存还是Perl内存?

c++ - 来自另一个 bool 函数的一个字符

php - 无法在 laravel 3 中捕获 PDOException

php - MySQL 和 PHP 的问题

Python zip 对两个 numpy 数组进行压缩

python - 我可以在不创建自己的计数器的情况下显示每个列表项在列表中的位置吗?

php - 如何在mysql中显示连续日期,如果日期不存在于表中