Check duplicate values in the array

Asked

Viewed 5,665 times

5

My question is this::

I have the following array:

$array = array(10, 30, 10, 40, 40);

I would like to know if there is a simple way to display the message: "there are duplicate values" or "there are no duplicate values".

The function array_count_values() could handle this array along with the foreach() comparing result to result until finding a quantity greater than 1. However, I would like to escape from this analysis, because I just need to know if duplicate values occur and not what these values are. Would anyone have any other idea?

  • Do you want to know if there are duplicate values on Aray or which one knows which duplicate values? For the first scenario the solution of @bfavaretto is perfect, for the second scenario the Idea was really useful array_count_values() with a foreach()

2 answers

8


One practical way (but I don’t know how to judge performance) is to filter duplicates to another array, and compare sizes:

$array = array(10, 30, 10, 40, 40);
$copia = array_unique($array);
if(count($copia) != count($array)) {
    echo "existem valores duplicados";
} else {
    echo "não existem valores duplicados";
}

Demo

  • The concern is precisely the performance. I had already thought about comparing the size of two arrays. I think your solution should be the simplest one.

  • 2

    For a simple analysis, both this solution is better and has better performance, for a more detailed analysis it would really be interesting to use the array_count_values()

  • Perfect solution. Thank you.

  • Excellent tip, I ended up taking advantage in my project today.

0

To display a shape using php’s native function array_diff_assoc:

<?php
    
    //array
    $arr = array(10, 30, 80, 40, 40);

    //function
    function checkDuplicateElementArray(array $arr){
        $toCompare = array_unique($arr);
        return array_diff_assoc($arr, $toCompare);
    }

    //use
    if(checkDuplicateElementArray($arr)){
        echo "Existem valores duplicados";
    }else{
        echo "Não existem valores duplicados";
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.