for 循环 vs while 循环 vs foreach 循环 PHP [英] for loop vs while loop vs foreach loop PHP

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

问题描述

第一次我是 PHP 新手.我一直在脚本中使用 for 循环、while 循环、foreach 循环.我不知道

1st off I'm new to PHP. I have been using for loop,while loop,foreach loop in scripts. I wonder

  • 哪个性能更好?
  • 选择循环的标准是什么?
  • 当我们在另一个循环中循环时应该使用哪个?

我不知道要使用哪个循环的代码.

the code which I'm stuck with wondering which loop to be used.

for($i=0;$i<count($all);$i++)
{
 //do some tasks here
 for($j=0;$j<count($rows);$j++)
 {
  //do some other tasks here 
 }
}

很明显,我可以使用 while 编写上述代码.希望有人能帮我弄清楚应该使用哪个循环更好.

It's pretty obvious that I can write the above code using while. Hope someone will help me out to figure out which loop should be better to be used.

推荐答案

哪个性能更好?

没关系.

选择循环的标准是什么?

what's the criteria to select a loop?

如果您只需要遍历对象或数组的所有元素,请使用 foreach.您需要 for 的情况包括

If you just need to walk through all the elements of an object or array, use foreach. Cases where you need for include

  • 当您明确需要对数字索引进行处理时,例如:
  • 当您需要在迭代中使用上一个或下一个元素时
  • 当您需要在迭代期间更改计数器时

foreach 更方便,因为它不需要您设置计数,并且可以通过任何类型的成员工作——无论是对象属性还是关联数组元素(它是for 不会被捕获).这通常最有利于可读性.

foreach is much more convenient because it doesn't require you to set up the counting, and can work its way through any kind of member - be it object properties or associative array elements (which a for won't catch). It's usually best for readability.

当我们在另一个循环中循环时应该使用哪个?

which should be used when we loop inside another loop?

两者都很好;在您的演示案例中,foreach 是最简单的方法.

Both are fine; in your demo case, foreach is the simplest way to go.

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

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