Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!