废话不多说,直接看如下代码:
<code><span>$arr</span> = <span>array</span>(<span>'a'</span>,<span>'b'</span>,<span>'c'</span>,<span>'d'</span>); <span>foreach</span>(<span>$arr</span><span>as</span> &<span>$v</span>){} <span>foreach</span>(<span>$arr</span><span>as</span><span>$v</span>){ var_dump(<span>$v</span>); }</code>
运行后,结果如下:
<code><span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) <span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span> //这里为什么是c呢?</span></code>
我们会诧异,为什么最后一个是c而不是d?
其实道理很简单,在第一次循环结束以后,变量v变成了arr[3]的引用。所以,当第二次使用foreach时,使用的是传值的方式,这种方式,其实就是遍历变量arr的值,然后把值赋给变量v,由于这时候变量v是arr[3]的引用,所以把值赋给变量v,其实就是赋给arr[3]。
我们把代码改一下:
<code><span>$arr</span> = <span>array</span>(<span>'a'</span>,<span>'b'</span>,<span>'c'</span>,<span>'d'</span>); <span>foreach</span>(<span>$arr</span><span>as</span> &<span>$v</span>){} <span>foreach</span>(<span>$arr</span><span>as</span><span>$v</span>){ var_dump(<span>$arr</span>);<span>//这里把变量$arr打印出来</span> }</code>
运行后,会发现:
<code>array (size=<span>4</span>) <span>0</span> => <span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) <span>1</span> => <span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) <span>2</span> => <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span>3</span> => &<span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) array (size=<span>4</span>) <span>0</span> => <span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) <span>1</span> => <span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) <span>2</span> => <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span>3</span> => &<span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) array (size=<span>4</span>) <span>0</span> => <span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) <span>1</span> => <span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) <span>2</span> => <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span>3</span> => &<span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) array (size=<span>4</span>) <span>0</span> => <span>string</span><span>'a'</span> (<span>length</span>=<span>1</span>) <span>1</span> => <span>string</span><span>'b'</span> (<span>length</span>=<span>1</span>) <span>2</span> => <span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>) <span>3</span> => &<span>string</span><span>'c'</span> (<span>length</span>=<span>1</span>)</code>
可以发现,arr[3]的值一直在改变。
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });版权声明:本文为博主原创文章,转载请注明出处。
以上就介绍了foreach中使用引用引起的问题,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。