Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda