使用 PHP 检查数组是否包含字符串中的重复值

Check if array contains a duplicate value in string with PHP

我想检查我的数组是否包含重复值。我有一个表格,我使用以下方法传递章节 ID:

<input name="chapter_id[]" type="number" value="<?= $row_chapter_list['chapter_id'] ?>">

要更新我的数据库,我选择这个输入并进行更新w/o任何问题:

if (isset($_POST['chapter_id'])) {
 
  // Update Kapitelnummer
  $statement = $pdo->prepare("UPDATE questionaire_chapter SET chapter_id = :chapter_id WHERE id = :id");
  $statement->bindParam(":chapter_id", $chapter_id, PDO::PARAM_STR);
  $statement->bindParam(":id", $id, PDO::PARAM_INT);
  foreach ($_POST['chapter_id'] as $index => $chapter_id) {
    $id = $_POST['chapter_inc_id'][$index];
    $statement->execute();
  }     
}

典型的 var_dump 结果如下所示:

array(3) { [0]=> string(1) "1" [1]=> string(2) "12" [2]=> string(2) "12" }

在此数组示例中,值“12”出现在两个字符串中。我想创建一个机制来计算双精度值并将结果用于 PHP if/else。我想避免将重复的章节 ID 写入我的数据库。

我第一次尝试计算字符串是这样的:

print_r(array_count_values($_POST['chapter_id']));

这给了我这样的结果

Array ( [1] => 1 [12] => 2 )

现在我缺少实现 if else 检查结果是否不为 1 的方法。 知道怎么做吗?

您可以使用 array_unique() 获取一个数组,其中已过滤掉所有重复项。使用它,您可以将它与原始数组进行比较:

if ($array != array_unique($array)) {
    echo "The arrays are not the same, which means that there are duplicates";
}