What are some best practices for handling unit conversions in PHP, especially when dealing with multiple units like grams, kilograms, milligrams, and liters?

When handling unit conversions in PHP, especially with multiple units like grams, kilograms, milligrams, and liters, it is essential to create a function that can convert between these units accurately. One approach is to define conversion factors for each unit and then use these factors to perform the conversions. Additionally, using a switch statement or associative array can help streamline the conversion process and make the code more readable.

function convertUnits($value, $fromUnit, $toUnit) {
    $conversionFactors = [
        'gram' => 1,
        'kilogram' => 1000,
        'milligram' => 0.001,
        'liter' => 1000
    ];

    if (!array_key_exists($fromUnit, $conversionFactors) || !array_key_exists($toUnit, $conversionFactors)) {
        return "Invalid unit provided";
    }

    $result = $value * ($conversionFactors[$fromUnit] / $conversionFactors[$toUnit]);
    return $result;
}

// Example usage
echo convertUnits(1000, 'gram', 'kilogram'); // Output: 1
echo convertUnits(500, 'milligram', 'gram'); // Output: 0.5