What is the best approach to output the value in an array that is closest to a calculated result in PHP?

When trying to find the value in an array that is closest to a calculated result in PHP, one approach is to iterate through the array and compare each value to the calculated result. Keep track of the value that is closest to the result by calculating the absolute difference between the value and the result. Update the closest value whenever a closer match is found.

<?php
// Array of values
$array = [10, 20, 30, 40, 50];

// Calculated result
$calcResult = 25;

// Initialize variables
$closestValue = null;
$closestDifference = PHP_INT_MAX;

// Iterate through the array
foreach($array as $value) {
    $difference = abs($value - $calcResult);
    if($difference < $closestDifference) {
        $closestValue = $value;
        $closestDifference = $difference;
    }
}

// Output the closest value
echo "Closest value to calculated result: " . $closestValue;
?>