检查字符串重复或不重复数据的最佳和快速方法是什么?

What is the best and fast way to check data in string duplicate or not?

检查字符串中是否重复数据的最佳和快速方法是什么?

$data = "320666,320372,320274,320728,320298,320797,320804,320831,320001,320409,320704,320680,320018,320565,320710,320455,320070,320095,320629,319919,320754,319921,320830,320869,320473,319936,320591,319891,320405,320788,320575,320730,320024,320452,320389,320289,320494,320290,319908,319926,320742,320546,319893,320602,320535,320288,320197,320613,320232,320513,320051,320360,319985,320852,320709,320352,320058,320791,320341,320133,319979,320361,319915,319912,320477,320311,320146,320325,320684,319935,320312,320159,320054,320737,320527,319907,320532,320208,320588,320632,320310,320837,320121,320291,320482,320316,320520,320583,320056,319897,320762,320366,319904,320169,320651,320751,320657,320374,320185,320821,319906,320039,320134,320507,319996,320277,320423,320803,320713,320456,320429,320189,320398,320813,320417,320302,320881,320200,320555,320740,320849,320432,320590,319948,319944,320313,320220,320094,320086,320000,320430,319968,320827,320424,320386,320687,320199,320785,320743,320167,320362,319939,320568,320422,320305,320082,320345,320652,320686,320209,320149,320211,320087,320767,320446,320388,320145,320469,320493,320801,319994,319899,320809,320781,320253,320498,320434,320109,319972,320838,320293,320639,320165,320420,320620,320164,320600,320612,320383,320574,320017,320470,319925,320226,320234,320585,320191,320510,319923,320690,319970,320337";

我该怎么做?

将这些值放入一个数组,删除重复值,然后将该数组与原始数组进行比较。如果它们相同,则没有重复。

$values = explode(',', $data);
var_dump($values == array_unique($values));

Demo

查看 php 手册中的 array_unique 函数:

 <?php
    $input = array("a" => "green", "red", "b" => "green", "blue", "red");
    $result = array_unique($input);
    print_r($result);
    ?>

甚至更快,但使用此函数的方法略有不同 - fast_unique

function fast_unique($input) {
    // Code documented at: http://www.puremango.co.uk/?p=1039
    return array_flip(array_flip(array_reverse($input,true)));
}

然后使用类似这样的方法从 $data 字符串创建一个数组:

$d = explode(',',$data);

echo "<pre>";
var_dump($d);
echo "</pre>";

使用explode函数拆分然后使用array_count_values

$arr = explode($data);

print_t(array_count_values($arr));

这将为您提供每个数字的重复计数,以便您可以检查计数是否大于 1,是否重复。