首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP FOR Iteration not iterating

PHP FOR Iteration not iterating
EN

Stack Overflow用户
提问于 2019-01-10 00:55:45
回答 1查看 74关注 0票数 2

有人知道为什么PHP中的for循环不能像预期的那样工作吗?请检查以下各项:

已查阅文档和谷歌关于运营商的信息:http://php.net/manual/en/language.operators.increment.php

代码语言:javascript
复制
<?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循环将像处理整数一样工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-10 01:04:50

您的循环没有迭代,因为条件失败-- 'Z‘大于'AL’。您可以使用strnatcmp()来完成您想要的操作:

代码语言:javascript
复制
for ($x = $a; strnatcmp($x, $b); $x++) {
    echo "The number is: $x\n";
}

输出:

代码语言:javascript
复制
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

实际上,编辑,嗯,这甚至不是必须的,只要检查一下不相等:

代码语言:javascript
复制
for ($x = $a; $x !== $b; $x++) {

注这可能会给你一个off-by one错误,这取决于你想要的输出是什么。如果你想再进行一次迭代,只需在循环前插入$b,或者像你的例子中那样使用while循环。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54114963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档