//Just cleaned the code up a bit.
function closestToZero(array $ints): int|float|null { if(!isset($ints[0])) return null; $closest = $ints[0]; foreach ($ints as $num) { $absNum = abs($num); $absClosest = abs($closest); if ($absNum < $absClosest) { $closest = $num; } elseif ($absNum === $absClosest && $num > $closest) { // Tie: prefer positive value $closest = $num; } } return $closest; } ?>
function closestToZero(array $ints) {$closest = 0;$result = 0;$total = count($ints);for($i=0; $i < $total; $i++)- function closestToZero(array $ints): int|float|null
- {
- if(!isset($ints[0])) return null;
- $closest = $ints[0];
- foreach ($ints as $num)
- {
$n = $ints[$i];$m = $n;if ($n == 0)- $absNum = abs($num);
- $absClosest = abs($closest);
- if ($absNum < $absClosest)
- {
return 0;}if ($n < 0)- $closest = $num;
- }
- elseif ($absNum === $absClosest && $num > $closest)
- {
$n *= -1;- // Tie: prefer positive value
- $closest = $num;
- }
if ($result + $m == 0){$result = $n;}if ($closest > $n || $i == 0) {$closest = $n;$result = $m;}}return $result;- }
- return $closest;
- }
- ?>