function findClosestToZero($arr) {
if (count($arr) < 2) {
echo "arr must have at least two elements.\n";
return;
}
// Step 1: Sort the arr
$sortedArr = $arr;
sort($sortedArr);
$left = 0;
$right = count($sortedArr) - 1;
$closestSum = PHP_INT_MAX;
$closestPair = [0, 0];
// Step 2: Use two-indexed technique
while ($left < $right) {
$sum = $sortedArr[$left] + $sortedArr[$right];
// Update closest sum and pair if needed
if (abs($sum) < abs($closestSum)) {
$closestSum = $sum;
$closestPair[0] = $sortedArr[$left];
$closestPair[1] = $sortedArr[$right];
}
// Move indexeds
if ($sum < 0) {
$left++; // Increase sum by moving left indexed
} else {
$right--; // Decrease sum by moving right indexed
}
}
// Output the result
echo "The two elements whose sum is closest to zero are: " .
$closestPair[0] . " and " . $closestPair[1] .
" with a sum of " . $closestSum . ".\n";
}
$arr = [23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31];
findClosestToZero($arr);
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/