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

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

问题描述

我现在正在阅读一本关于 PHP 的电子书,作者指出 while 循环和 for 循环之间的区别在于 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.

所以拿这个:

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

但这不是和

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

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

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)

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

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.

for 循环在这种情况下更具可读性,并且绝对是您会发现在几乎所有具有循环指令的语言中使用的约定.如果您使用 while 循环,人们会想为什么您没有使用 for 循环.

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天全站免登陆