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

查看:123
本文介绍了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.

推荐答案

哪个是性能更好的?

which one is better for performance?

没关系.

选择循环的标准是什么?

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