How can PHP be used to dynamically calculate prices based on weight conversions, such as converting grams to kilograms or milligrams to liters?

To dynamically calculate prices based on weight conversions in PHP, you can create a function that takes the weight in a base unit (such as grams or milligrams) and converts it to the desired unit (such as kilograms or liters). You can then use this function to calculate the price based on the converted weight.

function convertWeight($weight, $unit) {
    switch($unit) {
        case 'kilograms':
            return $weight / 1000;
            break;
        case 'liters':
            return $weight / 1000;
            break;
        // Add more conversion cases as needed
    }
}

$grams = 5000;
$pricePerKilogram = 10;
$price = convertWeight($grams, 'kilograms') * $pricePerKilogram;

echo "Price for 5 kilograms: $" . $price;