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?
Advertisement
Answer
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"; }