Learn how to find the closest value to zero from a collection of numbers inside an array in PHP.

On the last days, i needed to fill a codingame test that exposed the following problem that needed to be solved:

Chaud Codingame

In this exercise, you have to analyze records of temperature to find the closest to zero. Sample temperatures. Here, -1.7 is the closest to 0. Implement the function closestToZero to return the temperature closer to zero which belongs to the array ts.

  • If ts is empty, return 0 (zero).
  • If two numbers are as close to zero, consider the positive number as the closest to zero (eg. if ts contains -5 and 5, return 5).
Input:
  • Temperatures are always expressed with floating point numbers ranging from -273 to 5526.
  • ts is always a valid array and is never null.

Solution

Based on the exposed data, the following implementation solves the problem:

<?php

/**
 * From a collection of numbers inside an array, returns the closest value to zero.
 */
function computeClosestToZero(array $ts) {
    if(empty($ts)){
        return 0;
    }
    
    $closest = 0;
    
    for ($i = 0; $i < count($ts) ; $i++) {
        if ($closest === 0) {
            $closest = $ts[$i];
        } else if ($ts[$i] > 0 && $ts[$i] <= abs($closest)) {
            $closest = $ts[$i];
        } else if ($ts[$i] < 0 && -$ts[$i] < abs($closest)) {
            $closest = $ts[$i];
        }
    }
    
    return $closest;
}

You can test the code with different examples of your own:

$ts = [7,-10, 13, 8, 4, -7.2,-12,-3.7,3.5,-9.6, 6.5,-1.7, -6.2,7];
// Result: -1.7
echo "Result: " . computeClosestToZero($ts);

$ts = [5, 6, 7, 9 , 2, - 2];
// Result: 2
echo "Result: " . computeClosestToZero($ts);

$ts = [];
// Result: 0
echo "Result: " . computeClosestToZero($ts);

Alternatively, one of the solutions of the community includes as well this other option:

<?php

function closestToZero(array $ts)
{
    if (count($ts) === 0) return 0;
    
    $closest = $ts[0];

    foreach ($ts as $d) 
    {
        $absD = abs($d);
        $absClosest = abs($closest);
        if ($absD < $absClosest) 
        {
            $closest = $d;
        } 
        else if ($absD === $absClosest && $closest < 0) 
        {
            $closest = $d;
        }
    }
    
    return $closest;
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors