我有以下数组:
$check = array(
$_POST["list1"],
$_POST["list2"],
$_POST["list3"],
$_POST["list4"],
$_POST["list5"],
$_POST["list6"],
$_POST["list7"],
$_POST["list8"],
$_POST["list9"],
$_POST["list10"],
);
我想检查这个数组中所有的值是否唯一(0是唯一可以重复的值)。所以:1, 2, 5, 7, 7, 0, 0, 4, 2, 1 ->错误1,2,3,0,0,0,0,7,8,9 -> ok任何想法?
PHP5.3
$result = array_reduce ($check, function ($valid, $value) {
static $found = array();
if (!$valid || (($value != 0) && in_array($value, $found))) {
return false;
} else {
$found[] = $value;
return true;
}
}, true);
或
$counted = array_count_values($check);
unset($counted[0], $counted['0']); // Ignore "0" (dont know, if its an integer or string)
$valid = (count($counted) == array_sum($counted));
<?php
function isValidArray($array)
{
$found = array();
foreach($array as $item)
{
$item = (int) $item;
if($item == 0)
continue;
if(in_array($item, $found))
return false;
array_push($found, $item);
}
return true;
}
?>