Skip to content

Instantly share code, notes, and snippets.

@allucardster
Created January 13, 2020 22:49
Show Gist options
  • Save allucardster/fc44c7b0960bae2b2a8ba6fd9add6f1a to your computer and use it in GitHub Desktop.
Save allucardster/fc44c7b0960bae2b2a8ba6fd9add6f1a to your computer and use it in GitHub Desktop.
<?php
/*
Find value that occurs in odd number of elements.
*/
function oddOccurrencesInArray(array $arr) : int
{
foreach(array_count_values($arr) as $number => $count) {
if ($count % 2) {
return $number;
}
}
return 0;
}
$test = [9, 3, 9, 3, 9, 7, 9];
print_r(oddOccurrencesInArray($test)); // Result: 7
@pauloacosta
Copy link

Congratulations on your solution! I was not aware of the array_count_values function, so I had to implement something similar that worked, but not with the desired performance. Thank you for sharing your code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment