What are some efficient ways to handle dynamic unit conversions in PHP without resorting to nested loops or excessive if/else statements?

When handling dynamic unit conversions in PHP, one efficient way to avoid nested loops or excessive if/else statements is to use a mapping array that stores conversion factors for different units. By using this mapping array, you can easily look up the conversion factor based on the input and output units, simplifying the conversion process.

// Mapping array for unit conversions
$conversionFactors = [
    'meters_to_feet' => 3.28084,
    'feet_to_meters' => 0.3048,
    // Add more conversion factors as needed
];

function convertUnits($value, $inputUnit, $outputUnit) {
    global $conversionFactors;

    $conversionKey = $inputUnit . '_to_' . $outputUnit;

    if (array_key_exists($conversionKey, $conversionFactors)) {
        $conversionFactor = $conversionFactors[$conversionKey];
        return $value * $conversionFactor;
    } else {
        return 'Unsupported unit conversion';
    }
}

// Example usage
echo convertUnits(10, 'meters', 'feet'); // Output: 32.8084