Get duplicate vector values

1

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

I'm trying to do 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 thus returning, 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 this , but it did not work.

    
asked by anonymous 10.08.2018 / 15:29

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 )

no ideone

no sandbox

    
10.08.2018 / 15:45
1

Use the array_diff_key function instead of array_diff for this case.

print_r(array_diff_key($cdCursos, array_unique($cdCursos)));
    
10.08.2018 / 15:44