廢話不多說,直接看如下代碼:
<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教程有興趣的朋友有所幫助。