Home  >  Article  >  Backend Development  >  Remove duplicate values ​​from PHP array_PHP tutorial

Remove duplicate values ​​from PHP array_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:33763browse

To remove duplicate values ​​from an array, you can use the foreach method or the array_unique method. 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 class="brush:php;toolbar:false">";
print_r($arrT);
print_r($arrRF);
print_r($arrRS);
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 similar.

When testing $intTotal is greater than 10000 and $intRand is 100, the efficiency of using array_unique is higher than that of 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 $ The reason for the ratio of intTotal/$intRand is that it does not feel proportional to the change, but it basically follows that the larger the ratio, the better the performance of array_unique.

To sum up, 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?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752465.htmlTechArticleTo remove duplicate values ​​in an array, you can use the foreach method or the array_unique method. There are two types of code below. All methods have been used. ?php$arrF = array();$arrS = array();$...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn