PHP Comparison of Two Methods for Removing Duplicate Array Values

  • 2021-07-01 06:48:14
  • OfStack

To remove duplicate values from an array, you can use either the foreach method or the array_unique method, and the following code uses both methods.


<?php
$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<br/>";
$intStart1 = time();
$arrRS = array_unique($arrT);
$intEnd2 = time();
$intTime2 = $intEnd2-$intStart1;
echo "With array_unique function,Spend time:($intTime2)";
echo "<pre>";
print_r($arrT);
print_r($arrRF);
print_r($arrRS);
echo "</pre>";
?>

When $intTotal is small, for example, within 1000, the value of $intRand basically does not affect the result, and the execution time of both is similar.

When $intTotal is greater than 10000 and $intRand is 100, the efficiency of using array_unique is higher than that of foreach cycle judgment, $intRand=10, and the execution time of both is 1.

Therefore, it can be concluded that when the array capacity is small, roughly within 1000, the execution efficiency of using both is similar.

When the array capacity is relatively large (I didn't test the specific value in detail, and those who are interested can determine this value under 1), with the gradual increase of $intRand, array_unique performs better. I don't use the ratio of $intTotal/$ intRand because the feeling does not change proportionally, but basically it will follow that the larger the ratio, the better the performance of array_unique.

To sum up, it is recommended to use array_unuique when filtering duplicate values of arrays. When the array is small, the efficiency of the two is equal, while the use of array_unique certainly reduces several lines of your code 1. When the array capacity is too large, the function performs better. Why not use it?


Related articles: