循环声明内的函数?
举个例子:
foreach(explode(' ','word1 word2 word3') as $v)
echo $v;
据我所知,php不会在每次explode函数时执行,但只会在第一次执行。
这是真的吗?即使对于用户定义的函数也是如此吗?
该代码比这个更好还是相等?
$genericVar = explode(' ','word1 word2 word3');
foreach($genericVar as $v)
echo $v;
谢谢
take this example:
foreach(explode(' ','word1 word2 word3') as $v)
echo $v;
From what I know php doens't execute every time the explode function, but it will be executed only the first time.
Is this true? And is this true even for user-defined functions?
Is that code better than this or it's equal?
$genericVar = explode(' ','word1 word2 word3');
foreach($genericVar as $v)
echo $v;
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
单独的代码更好,因为它提高了可读性,并且维护代码会更容易。
永远不要为了删除一些行并使其看起来紧凑而将语句相互填充。当然,您将能够节省一些字节,但这些字节稍后会在维护它时困扰您。
The separate code is better because it improves readability and maintaining the code will be easier.
Never stuff statements into each other just to remove some lines and make it look compact. Sure, you will be able to save some bytes, but those bytes will bite you later while maintaining it.
foreach
使用给定数组的副本,因此该函数只会执行一次。但这是行不通的:
在这里你必须将分解的数组存储在一个单独的变量中。
foreach
uses a copy of the given array, so the function will be executed only once.but this wont work:
Here you have to store the exploded array in a separate variable.
使用foreach时,这两段代码是等价的。函数explode只会被调用一次。
但是,这不是它在for循环中的工作方式,例如:
在本例中,count函数将在每次迭代时被调用。
When using foreach, the two pieces of code are equivalent. The function explode will only be called once.
However, this is not how it works with for loops, for example :
In this example, the count function will be called at each iteration.