Skip to content

Instantly share code, notes, and snippets.

@didagu
Last active March 16, 2020 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didagu/4dd8e75ddeb0aaedb789f813c9d5a0c1 to your computer and use it in GitHub Desktop.
Save didagu/4dd8e75ddeb0aaedb789f813c9d5a0c1 to your computer and use it in GitHub Desktop.
function that gets the item that occurred an odd number of times in an array.
<?php
// first solution
function getOddOccurrenceFromArray1($arr)
{
$result = 0;
for ($i = 0; $i < sizeof($arr); $i++)
/*
* Using xor bitwise operator, the final value of $result will
* be the array item that occurred an odd number of time
*/
$result = $result ^ $arr[$i];
return $result;
}
//second solution
function getOddOccurrenceFromArray2($arr) {
$countedArray = array_count_values($arr);
$filteredArray = array_filter($countedArray, function ($value, $key) {
return $value % 2 != 0 ;
}, ARRAY_FILTER_USE_BOTH);
$arrayKeys = array_keys($filteredArray);
return $arrayKeys[0];
}
/*
* input array: [1,1,1,3,4]
*/
/*
* output: 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment