How to find an element that appears once in an array of elements that appears three times in PHP

1 Answer

0 votes
function findElementThatAppearsOnceInArray($arr) {
    $map = array();
    
    foreach ($arr as $x) {
        $map[$x] = ($map[$x] ?? 0) + 1;
    }
    
    foreach ($map as $key => $value) {
        if ($value == 1) {
            return $key;
        }
    }
    
    return -1;
}

$arr = array(3, 5, 5, 2, 7, 3, 2, 8, 8, 3, 2, 5, 8);

echo findElementThatAppearsOnceInArray($arr);



/*
run:

7

*/

 



answered Jul 8, 2024 by avibootz
...