PHP LogoCurrency Converter

A Currency Converter is a tool that calculates the equivalent value of a certain amount of money from one currency into another. Its primary purpose is to facilitate transactions, financial planning, travel budgeting, and understanding international trade by providing an estimate based on current or historical exchange rates.

The core mechanism involves three main components:
1. Input Amount: The numerical value of money the user wishes to convert.
2. Source Currency: The original currency of the input amount (e.g., USD, EUR, TRY).
3. Target Currency: The currency into which the input amount is to be converted (e.g., EUR, JPY, GBP).
4. Exchange Rate: The value of one currency expressed in terms of another. For example, if 1 USD = 0.92 EUR, then the exchange rate from USD to EUR is 0.92.

How it works:
The conversion process typically involves fetching the latest exchange rates. In a simple implementation, these rates might be hardcoded or stored in a database. For a more robust and real-time solution, a currency exchange rate API (Application Programming Interface) is often used to retrieve up-to-date rates from financial data providers. Once the rate between the source and target currency is obtained, the input amount is multiplied by this rate to yield the converted value.

Key Considerations:
* Data Source for Rates: The accuracy of the conversion heavily depends on the source of exchange rates. Static rates are easy to implement but quickly become outdated. Dynamic rates from APIs provide real-time accuracy but require internet connectivity and often an API key.
* Direct vs. Indirect Rates: Sometimes a direct rate between two currencies isn't available, or it's more accurate to convert via a common base currency (e.g., USD or EUR). For example, to convert TRY to JPY, one might convert TRY to USD, and then USD to JPY.
* Rounding: Currency conversions often result in decimal numbers. Proper rounding (e.g., to two decimal places for most currencies) is crucial for practical use.
* Error Handling: The system should gracefully handle cases like invalid currency codes, missing exchange rates, or issues with the API connection.
* Spreads/Fees: Real-world currency exchange often involves spreads (the difference between buying and selling rates) or transaction fees, which a simple converter might not account for.

In summary, a currency converter is an essential tool in a globalized world, bridging financial understanding across different economies by providing a clear, albeit often simplified, representation of monetary value.

Example Code

<?php

class CurrencyConverter {
    private $exchangeRates; // A simple array to store rates for demonstration

    public function __construct() {
        // In a real-world application, these rates would come from an API,
        // a database, or an external service. For this example, we'll hardcode some direct conversion rates.
        $this->exchangeRates = [
            'USD' => [
                'EUR' => 0.92,
                'GBP' => 0.79,
                'JPY' => 155.00,
                'TRY' => 32.20,
                'CAD' => 1.37,
                'USD' => 1.00 // Self conversion
            ],
            'EUR' => [
                'USD' => 1.08,
                'GBP' => 0.86,
                'JPY' => 168.00,
                'TRY' => 34.90,
                'CAD' => 1.48,
                'EUR' => 1.00
            ],
            'GBP' => [
                'USD' => 1.26,
                'EUR' => 1.16,
                'JPY' => 195.00,
                'TRY' => 41.00,
                'CAD' => 1.73,
                'GBP' => 1.00
            ],
            'TRY' => [
                'USD' => 0.031, // 1 TRY = 0.031 USD (approx)
                'EUR' => 0.028, // 1 TRY = 0.028 EUR (approx)
                'GBP' => 0.024, // 1 TRY = 0.024 GBP (approx)
                'JPY' => 4.80,  // 1 TRY = 4.80 JPY (approx)
                'CAD' => 0.043, // 1 TRY = 0.043 CAD (approx)
                'TRY' => 1.00
            ],
             'JPY' => [
                'USD' => 0.0064, // 1 JPY = 0.0064 USD (approx)
                'EUR' => 0.0059, // 1 JPY = 0.0059 EUR (approx)
                'GBP' => 0.0051, // 1 JPY = 0.0051 GBP (approx)
                'TRY' => 0.20,   // 1 JPY = 0.20 TRY (approx)
                'CAD' => 0.0088, // 1 JPY = 0.0088 CAD (approx)
                'JPY' => 1.00
            ],
            'CAD' => [
                'USD' => 0.73,
                'EUR' => 0.67,
                'GBP' => 0.58,
                'JPY' => 113.00,
                'TRY' => 23.30,
                'CAD' => 1.00
            ]
        ];
    }

    /
     * Converts an amount from a source currency to a target currency.
     *
     * @param float $amount The amount to convert.
     * @param string $sourceCurrency The currency code of the source (e.g., 'USD').
     * @param string $targetCurrency The currency code of the target (e.g., 'EUR').
     * @return float|null The converted amount, or null if conversion is not possible.
     */
    public function convert(float $amount, string $sourceCurrency, string $targetCurrency): ?float {
        // Convert currency codes to uppercase for consistency
        $sourceCurrency = strtoupper($sourceCurrency);
        $targetCurrency = strtoupper($targetCurrency);

        // Check if source currency is supported
        if (!isset($this->exchangeRates[$sourceCurrency])) {
            return null; // Source currency not supported
        }

        // Check if target currency is supported from the perspective of the source
        if (!isset($this->exchangeRates[$sourceCurrency][$targetCurrency])) {
            return null; // Target currency not directly convertible from source, or not supported
        }

        // If source and target are the same, the rate is 1.00 (handled in array)

        $rate = $this->exchangeRates[$sourceCurrency][$targetCurrency];
        return round($amount * $rate, 2); // Round to 2 decimal places for typical currency precision
    }
}

// --- Usage Example ---
$converter = new CurrencyConverter();

echo "--- Conversion Examples ---\n\n";

$amount = 100;
$source = 'USD';
$target = 'EUR';
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates.\n";
}

$amount = 500;
$source = 'TRY';
$target = 'USD';
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates.\n";
}

$amount = 75;
$source = 'GBP';
$target = 'JPY';
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates.\n";
}

echo "\n--- Error Handling Examples ---\n\n";

$amount = 25;
$source = 'XYZ'; // Invalid currency
$target = 'EUR';
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates (Source XYZ).\n";
}

$amount = 50;
$source = 'USD';
$target = 'ABC'; // Invalid target currency (not in hardcoded rates)
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates (Target ABC).\n";
}

echo "\n--- Self Conversion Example ---\n\n";

$amount = 100;
$source = 'USD';
$target = 'USD';
$convertedAmount = $converter->convert($amount, $source, $target);

if ($convertedAmount !== null) {
    echo "{$amount} {$source} is equal to {$convertedAmount} {$target}\n";
} else {
    echo "Failed to convert {$amount} {$source} to {$target}. Check currency codes or rates.\n";
}

?>