0

I want to check if my array contains a duplicate value. I have a form where i pass a Chapter ID with the following method:

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

To update my database i pick this input and do the update w/o any issues:

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

A typical var_dump result looks like:

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

In this array example the value "12" is present in two strings. I would like to create a mechanic to count double values and and use the result in a PHP if/else. i want to avoid that the a duplicate chapter ID gets written into my database.

My first try to count the string is this:

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

Which gives me a result like this

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

Now i am missing the method to implement a if else to check if the result is not 1. Any idea how to do this?

5
  • Can't you just filter away the duplicates with array_unique()? Commented Jan 10, 2022 at 13:03
  • No because if there is a duplicate i will not initiate my Update query and give a warning to the user. Is there any function like "if is not unique" ? Commented Jan 10, 2022 at 13:05
  • 2
    You could do: if ($array != array_unique($array)) { echo "there are duplicates"; } Commented Jan 10, 2022 at 13:09
  • Thank you! thats exaclty what i was looking for. Please make the answer. Commented Jan 10, 2022 at 13:11
  • 1
    Or count(array_unique($array)) == count($array) Commented Jan 10, 2022 at 13:15

1 Answer 1

2

You can use array_unique() to get an array where any duplicates has been filtered out. Using that, you can compare it to the original array:

if ($array != array_unique($array)) {
    echo "The arrays are not the same, which means that there are duplicates";
}
Sign up to request clarification or add additional context in comments.

1 Comment

$array = $_POST['chapter_id']; To make it complete ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.