PHP for迭代不迭代

问题描述 投票:2回答:1

有谁知道为什么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循环将在整数处理时起作用。

php perl for-loop
1个回答
5
投票

你的循环没有迭代,因为条件失败 - '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循环。

© www.soinside.com 2019 - 2024. All rights reserved.