php數組 過濾掉PHP數組中的重複值的實現代碼

來源:互聯網
上載者:User
複製代碼 代碼如下:


$arrF = array();
$arrS = array();
$intTotal = 100;
$intRand = 10;
for($i=0; $i < $intTotal; $i++)
{
$arrF[] = rand(1, $intRand);
$arrS[] = rand(1, $intRand);
}
$arrT = array_merge($arrF, $arrS);
$arrRF = array();
$intStart = time();
foreach($arrT as $v)
{
if(in_array($v, $arrRF))
{
continue;
}
else
{
$arrRF[] = $v;
}
}
$intEnd = time();
$intTime = $intEnd-$intStart;
echo "With Continue,Spend time:$intTime
";
$intStart1 = time();
$arrRS = array_unique($arrT);
$intEnd2 = time();
$intTime2 = $intEnd2-$intStart1;
echo "With array_unique function,Spend time:($intTime2)";
echo "

"; 
print_r($arrT);
print_r($arrRF);
print_r($arrRS);
echo "
";
?>


在$intTotal比較小的情況下,比如說1000以內,$intRand的取值基本不影響結果,兩者執行的時間都差不多。
測試$intTotal 大於10000時,$intRand取值100時,使用array_unique的效率要高於foreach迴圈判斷,$intRand=10,兩者執行時間一致。
因此,可以得出結論,當數組容量不大,大概在1000以內時,使用兩者的執行效率差不多。
當數組容量比較大時(具體應該到什麼值,我沒有詳細測試,感興趣的可以確定一下這個值),隨著$intRand的逐漸增大,array_unique的表現更好,我不使用$intTotal/$intRand這個比值,是因為,感覺並不是成比例變化,但是基本會遵循比值越大,array_unique表現越好。
綜上所述,在過濾數組重複值的時候,建議使用array_unuique,數組不大的時候兩者效率等同,而array_unique使用當然讓你的代碼一下子減了好幾行,數組容量過大時,函數的表現更好,為什麼不用呢?

以上就介紹了php數組 過濾掉PHP數組中的重複值的實現代碼,包括了php數組方面的內容,希望對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.