How to extract the unique integers from an array excluding duplicates in PHP

1 Answer

0 votes
function getUniqueExcludeDuplicates($arr) {
    // Array to count occurrences of each number
    $frequency = [];

    // Count frequencies of each number in the array
    foreach ($arr as $num) {
        if (isset($frequency[$num])) {
            $frequency[$num]++;
        } else {
            $frequency[$num] = 1;
        }
    }

    // Collect numbers that appear only once
    $result = [];
    foreach ($arr as $num) {
        if ($frequency[$num] == 1) {
            $result[] = $num; // Add to result if it's truly unique
        }
    }

    return $result;
}

$arr = [1, 2, 3, 5, 8, 3, 1, 1, 0, 6, 5, 7, 3, 1, 4, 9];

// Call the function to exclude duplicates
$uniqueValues = getUniqueExcludeDuplicates($arr);

echo "Unique values (excluding duplicates): ";
foreach ($uniqueValues as $num) {
    echo $num . " ";
}
echo PHP_EOL;


  
/*
run:
      
Unique values (excluding duplicates): 2 8 0 6 7 4 9 

*/
 

 



answered Mar 28, 2025 by avibootz
...