Copy code The code is as follows:
$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 "
"; <br>print_r($arrT); <br>print_r($arrRF); <br>print_r($arrRS); <br>echo "
";
?>
When $intTotal is relatively small, for example, within 1000, the value of $intRand basically does not affect the result, and the execution time of both is almost the same.
When testing $intTotal greater than 10000, when $intRand is 100, the efficiency of using array_unique is higher than the foreach loop judgment, $intRand=10, the execution time of the two is consistent.
Therefore, it can be concluded that when the array capacity is not large, probably within 1000, the execution efficiency of using the two is similar.
When the array capacity is relatively large (I have not tested the specific value, you can determine this value if you are interested), as $intRand gradually increases, array_unique performs better, I do not use $intTotal/ The reason for the ratio of $intRand is that it does not feel to change proportionally, but it basically follows that the larger the ratio, the better the performance of array_unique.
In summary, when filtering duplicate values in an array, it is recommended to use array_unuique. When the array is small, the efficiency of the two is the same. Using array_unique will of course reduce your code by several lines. When the array capacity is too large, the function performs better, why not use it?
The above introduces the implementation code of PHP array to filter out duplicate values in PHP array, including the content of PHP array. I hope it will be helpful to friends who are interested in PHP tutorials.