在foreach循环中声明的PHP变量在每次迭代中被破坏和重新创建? [英] Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?

查看:287
本文介绍了在foreach循环中声明的PHP变量在每次迭代中被破坏和重新创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  foreach($ myArray as $ myData){
$ myVariable ='x';
}

PHP是否会破坏它,并在每次迭代中重新创建它?换句话说,在性能方面做得更聪明:

  $ myVariable; 
foreach($ myArray as $ myData){
$ myVariable ='x';
}

预先感谢您的见解。

解决方案

在您的第一个示例中:

  foreach($ myArray as $ myData){
$ myVariable ='x';

$ / code>

$ myVariable 是在第一次迭代期间创建并且在每次进一步的迭代上被重写。

在第二个例子中:

  $ myVariable; 
foreach($ myArray as $ myData){
$ myVariable ='x';

$ / code>

$ myVariable 是在任何迭代之前创建并设置为null。在每次迭代期间,如果将被覆盖。在离开你的脚本,函数,方法的范围之前,它不会被销毁。

更新



我错过了提到的主要区别。 ( $ myArray )为空
会在您的第一个示例中创建不是,但在您的第二个示例中,它的值将为null。


If I declare a variable inside a foreach loop, such as:

foreach($myArray as $myData) {
    $myVariable = 'x';
}

Does PHP destroy it, and re-creates it at each iteration ? In other words, would it be smarter performance-wise to do:

$myVariable;
foreach($myArray as $myData) {
    $myVariable = 'x';
}

Thank you in advance for your insights.

解决方案

In your first example:

foreach($myArray as $myData) {
    $myVariable = 'x';
}

$myVariable is created during the first iteration and than overwritten on each further iteration. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

In your second example:

$myVariable;
foreach($myArray as $myData) {
    $myVariable = 'x';
}

$myVariable is created before any iteration and set to null. During each iteration if will be overwritten. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

Update

I missed to mention the main difference. If $myArray is empty (count($myArray) === 0) $myVariable will not be created in your first example, but in your second it will with a value of null.

这篇关于在foreach循环中声明的PHP变量在每次迭代中被破坏和重新创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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