Filter out the duplicate values in the PHP array implementation code _php tips

Source: Internet
Author: User
Tags rand
Copy code code as follows:

<?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/>";
$intStart 1 = time ();
$arrRS = Array_unique ($arrT);
$intEnd 2 = time ();
$intTime 2 = $intEnd 2-$intStart 1;
echo "With Array_unique function,spend Time: ($intTime 2)";
echo "<pre>";
Print_r ($arrT);
Print_r ($arrRF);
Print_r ($arrRS);
echo "</pre>";
?>

In the case of $inttotal relatively small, for example 1000, the value of the $intRand will not affect the results, both the execution time is similar.

When the test $inttotal is greater than 10000, the efficiency of using array_unique is higher than that of the Foreach loop, $intRand = 10, and the execution time is the same when the $intRand takes a value of 100.

Therefore, it can be concluded that the execution efficiency of the two is almost the same when the size of the array is less than 1000.

When the size of the array is relatively large (what should be the value, I do not have a detailed test, interested to determine the value), as $intrand gradually increased, array_unique performance better, I do not use the $inttotal/$intRand this ratio, is because, The feeling is not proportional change, but basically will follow the ratio is bigger, array_unique performance is better.

To sum up, in the filtering of the array of duplicate values, the proposed use of Array_unuique, the array is not when the two efficiency equivalent, and array_unique use of course to let your code lost a few lines, the array capacity is too large, function performance better, why not?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.