PHP中For、While、Foreach迴圈的比較____PHP

來源:互聯網
上載者:User

在使用PHP作為程式設計語言的過程中,我們經常會遇到需要將一段代碼執行多次的情況。這時就需要用到PHP迴圈了。PHP提供了三種不同類型的迴圈供你在合適的情境中使用: For 迴圈 While 迴圈 Foreach 迴圈 For迴圈

for迴圈用於已經確定將你的運算式需要執行多少次的情況。

文法:

for (initialization; condition; increment){    code to be executed;}
<?phpfor($i=1; $i<=100000; $i++){    echo "The number is " . $i . "<br>";}?>
While迴圈

while運算式將會執行一段代碼直到條件陳述式為false。While迴圈通常更適合資料庫相關操作。

文法:

while (condition){    code to be executed;}
<!--?php// If you had an array with fruit names and prices in you could use foreach$fruit = array(     "orange" =--> "5.00",     "apple" => "2.50",     "banana" => "3.99" ); foreach ($fruit as $key => $value) {     "$key is $value dollars ";} ?>
三種迴圈的比較

我們知道在PHP中有多種迴圈,現在我們需要知道哪種迴圈更加高效,以便於我們編寫的應用更快。

下面我們開始實驗進行對比. While迴圈 vs. For迴圈

<?php    // While Loop    $a=0;    while($a < 1000)    {        $a++;    }?>

VS.

<?php    // For Loop    for($a = 0; $a < 1000;)    {        $a++;    }?>

上述實驗證明While迴圈比For迴圈執行效率要高出19.71%。因此,推薦儘可能的使用while迴圈而不是For迴圈。 For迴圈 vs Foreach迴圈

<?php    $test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me");    $keys = array_keys($test);    $size = sizeOf($keys);    for($a = 0; $a < $size; $a++)    {        $t = $test[$keys[$a]];    }?>

VS.

<?php    $test = array(1 => "cat", "dog" => 0, "red" => "green", 5 => 4, 3, "me");    foreach($test as $t){        }?>

上述實驗證明Foreach 迴圈比For迴圈快141.29%! 結論

這些迴圈通常用於實現不同的目的,現在我們知道了各個迴圈在執行效率上的表現。當需要追求執行效率的時候,我們通常推薦使用while迴圈來代替for迴圈。同樣的在foreach迴圈和loop迴圈之間,儘可能的使用foreach迴圈。下一步,我們將會研究如何有效地在模板中使用迴圈。請繼續關注。


原文:http://www.codeproject.com/Tips/1078835/Loops-in-PHP

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.