PHP中的while循环和for循环之间的区别? [英] Differences between a while loop and a for loop in PHP?

查看:202
本文介绍了PHP中的while循环和for循环之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读PHP上的电子书,作者指出,while循环和for循环的区别在于for循环会计算它运行的次数。



所以拿这个:

$ p $ <?php
for($ i = 1; $ i <10; $ i = $ i + 1){
printNumber $ i \\\
;
}
?>

但是这不会是相同的

 <?php 
$ i = 1;
while($ i <10){
$ i = $ i + 1;
打印Number $ i \\\
;
}
?>

或者还有其他一些他没有指出的区别吗? (除了使用while循环,当你不确定条件将保持多长时间,比如从数据库中选择行)

我的意思是,如果这是只有区别,不能我只是不使用for循环,而是使用while循环吗?

解决方案

你能吗?是的,当然了。但是不管你是否应该是一个完全不同的问题。
$ b $ for 循环在这种情况下更具可读性,这绝对是你在几乎所有具有循环指令的语言中都能找到的惯例。如果你在循环中使用,人们会怀疑为什么你没有使用作为循环。


I'm reading an ebook on PHP right now, and the author noted that the difference between a while loop and a for loop is that the for loop will count how many times it runs.

So take this:

<?php
    for ($i = 1; $i < 10; $i = $i + 1) {
        print "Number $i\n";
    }
?> 

But wouldn't this be the same as

<?php
    $i = 1;
        while ($i < 10) {
            $i = $i + 1;
            print "Number $i\n";
        }
?>

Or is there some other differences that he didn't point out? (Aside from using while loop for when you're unsure of how long the condition will remain true, such as selecting rows from a database)

I mean, if that's the only difference, can't I just not use the for loop and use the while loop instead?

解决方案

Can you? Yes, certainly. But whether or not you should is an entirely different question.

The for loop is more readable in this scenario, and is definitely the convention you'll find used within virtually every language that has looping directives. If you use the while loop, people are going to wonder why you didn't use a for loop.

这篇关于PHP中的while循环和for循环之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆