检查数组是否唯一(但0可以重复)

时间:2011-07-15 10:47:25

标签: php

我有以下数组:

$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->好 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

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));

答案 1 :(得分:0)

<?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;
    }
?>