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

264
Views
Find duplicate items in array

I'm trying to achieve to check if my array has duplicate items. But in my special case i need to use two dimensional array.

For an array that has 10 items, i managed to build this code, and i am storing values that i need to validate if they have a duplicate value or not is: $array[0][0], $array[1][0], $array[2][0]...

$arrayItemCount = 10; //means $array[0][0] to $array[9][0]
    for ($p=0;$p<$arrayItemCount;$p++){
        for ($h=0;$h<$arrayItemCount;$h++){
            if ($array[$p][0]==$array[$h][0]){
                $duplicate++;
            }
        }
    }

I am not an expert when it comes to arrays, so any help would be appreciated.

Expected result:

$array[0][0] = 5;
$array[1][0] = 99;
$array[2][0] = 5;

echo $duplicate; //1 or true
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A recursive function can be used to find duplicate values regardless of the number of dimensions.

function hasDuplicates(array $array, array &$values = []): bool
{
    foreach ($array as $value) {
        if (is_array($value)) {
            if (hasDuplicates($value, $values)) return true;
        } else {
            if (isset($values[$value])) return true;
            $values[$value] = 1;
        }
    }
    return false;
}

In this example, $values is a reference to an array that keeps track of all the numbers that have been evaluated so far. Any time a non-array value is encountered, the function will try to find it in $values. If it's found, the function will immediately return true (and recursively return true to the outermost function call).

If the entire array is traversed without finding a duplicate, it will return false.

$hasDuplicates = hasDuplicates($your_array);
over 4 years ago · Santiago Trujillo 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!