Get duplicate values from Vector

Asked

Viewed 35 times

1

I would like to get only the values that are duplicated in the array

I’m trying to do it like this:

$cdCursos = array(1, 2,3,4,5,3 );           
echo "<pre>";
print_r( $cdCursos );
echo "</pre>";
$withoutDup  = array_unique($cdCursos);
echo "<pre>";
print_r( $withoutDup );
echo "</pre>";
$duplicates  = array_diff($cdCursos, $withoutDup);
echo "<pre>";
print_r( $duplicates );
echo "</pre>";

The values are returning so, respectively:

Array
(
    [0] => 1
    1 => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 3
)
Array
(
    [0] => 1
    1 => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

</pre><pre>Array ( )

I tried to that one answer, but it did not work

2 answers

2


$arr = array(1, 2,3,4,5,3);

$uarr = array_unique($arr); 

print_r($uarr); //Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 

echo "<br>";
echo "<br>";

var_dump(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr)))); //array(2) { [2]=> int(3) [5]=> int(3) } 

echo "<br>";
echo "<br>";
$unicos=(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr))));

print_r($unicos); //Array ( [2] => 3 [5] => 3 )

in the ideone

in the sandbox

  • Good, boy! Exactly what I wanted. Thank you very much

1

Use the function array_diff_key instead of array_diff for this case.

print_r(array_diff_key($cdCursos, array_unique($cdCursos)));

Browser other questions tagged

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