Skip to content

Instantly share code, notes, and snippets.

@kapolos
Created September 4, 2015 06:56
Show Gist options
  • Save kapolos/85ed05c31340714c9f88 to your computer and use it in GitHub Desktop.
Save kapolos/85ed05c31340714c9f88 to your computer and use it in GitHub Desktop.
/**
* Checks if the sum of any 2 values of the array equals to $sum
* Assumes a non-associative array with numeric values
*
* @param array $arr
* @param integer $sum
*
* @return bool
*/
function checkSumExists(array $arr, $sum)
{
sort($arr, SORT_NUMERIC);
$topdown = 0;
$downup = count($arr) - 1;
while ($topdown < $downup) {
$step = $arr[$topdown] + $arr[$downup];
switch (TRUE) {
case ($step == $sum):
return TRUE;
break;
case ($step < $sum):
$topdown++;
break;
case ($step > $sum):
$downup++;
break;
}
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment