Skip to content
Advertisement

avoid same numbers and zero in array

I have a form with that table: jsfiddle

In this form i need to enable to edit the number fields.
After submit i collect the data and write to mysql.

<?php
foreach ($_POST['number'] as $key => $val) 
{
    $number                 = $_POST['number'][$key];
    $name                   = $_POST['name'][$key];
    $description            = $_POST['description'][$key];
    
    if (!empty($number)) 
    {
        $query = "INSERT INTO TEST SET date=NOW(), id='$number', name='$name', description='$description'";
        $insert = $connect->query($query) or die($connect->error . __LINE__);
    }

}
?>

Before mysql insert i want to check that the $number array does not contain the same numbers and zero (like: 0,1,1,101,150).
If yes give an error to the user that the Number field need to be unique.
How can I do that the easiest way with php or javascript? thanx 😉

Advertisement

Answer

<?php
$arrayDuplicates = [1, 2, 3, 1, 2, 3, 1, 2, 3];
$arrayNoDuplicates = [1, 2, 3, 4];

echo 'arrayDuplicates: ';
if(count($arrayDuplicates) != count(array_unique($arrayDuplicates)))
    echo 'duplicates found <br>';
else echo 'no duplicates <br>';

echo 'arrayNoDuplicates: ';
if(count($arrayNoDuplicates) != count(array_unique($arrayNoDuplicates)))
    echo 'duplicates found <br>';
else echo 'no duplicates <br>';

Output:

arrayDuplicates: duplicates found 
arrayNoDuplicates: no duplicates

array_unique is going to give you an array that contains only the unique elements. That means, if an element has duplicates, count(array_unique($array)) is going to be smaller than count($array).

Check array_unique here: https://www.php.net/manual/en/function.array-unique.php

Edit: I suggest reading other people’s comments about improving your code, too.

Forgot for zero.

$arrayZero = [0, 1, 2, 3];
$arrayNoZero = [1, 2, 3];

echo 'arrayZero: ';
if(in_array(0, $arrayZero)) echo 'has zero. <br>';
else echo 'no zero. <br>';

echo 'arrayNoZero: ';
if(in_array(0, $arrayNoZero)) echo 'has zero. <br>';
else echo 'no zero. <br>';

To check if an element is in an array (if array contains 0, for example) you can use in_array.

Check in_array here: https://www.php.net/manual/en/function.in-array.php

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement