Search code examples
phpcurrencyintl

Get currency code based on symbol


I am currently working with an API where instead of floats or integers for currency I receive strings like these.

  • $2.49
  • £2.49
  • €2.49
  • etc.

The issue with that is that I need to store the value and currency separately but the currency needs to be stored as ISO Code, so for example EUR, USD or GBP instead of € and $.

Is there any way in PHP to get the currency code based on a currency symbol using the NumberFormatter or something like that?

Currently I just have a very long list of currency symbols and names which I use to do things like string_contains('$2.49', '$') to check for a certain currency.


Solution

  • You could work with NumberFormatter::parseCurrency:

    <?php
    $fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    
    echo "#1: ".$fmt->parseCurrency("$2.49", $curr)." in $curr<br>";
    echo "#2: ".$fmt->parseCurrency("£2.49", $curr)." in $curr<br>";
    echo "#3: ".$fmt->parseCurrency("€2.49", $curr)." in $curr<br>";
    ?>
    

    Prints:

    #1: 2.49 in USD
    #2: 2.49 in GBP
    #3: 2.49 in EUR
    

    Note that Richard's comment about multiple currencies using the same symbol still applies but might be handled by specifying different locales for the NumberFormatter:

    <?php
    $fmt = new NumberFormatter('en_AU', NumberFormatter::CURRENCY);
    
    echo "#1: ".$fmt->parseCurrency("$2.49", $curr)." in $curr<br>";
    ?>
    

    Would e.g. change the first output to:

    #1: 2.49 in AUD