How can one efficiently sort an array in PHP to find the closest value to a given result?

To efficiently sort an array in PHP to find the closest value to a given result, you can sort the array in ascending order and then iterate through the array to find the closest value to the given result. You can calculate the absolute difference between each element in the array and the given result, keeping track of the closest value found so far. Finally, return the closest value.

function findClosestValue($arr, $result) {
    sort($arr);
    $closest = $arr[0];
    $minDiff = abs($arr[0] - $result);

    foreach ($arr as $value) {
        $diff = abs($value - $result);
        if ($diff < $minDiff) {
            $closest = $value;
            $minDiff = $diff;
        }
    }

    return $closest;
}

// Example usage
$array = [3, 7, 11, 15, 20];
$result = 10;
$closestValue = findClosestValue($array, $result);
echo "Closest value to $result is: $closestValue";