I was working on an integration with Stripe payment processing gateway. The integration required that we retrieve prior payments from a customer and display them on the website. When Stripe returns the customer’s payment information, it also sends the currency that the payment was made in. However, it only sends the three digit currency code (i.e. usd, gbp, cad, etc.) along with the payment information. When displaying the amount that was paid, it would be nice to show the currency symbol instead of the three digit currency code like $10 instead of usd 10.
How to Get Currency Symbols from Three Digit Currency Code
In my case, I was using Stripe, but you can easily use this example on any number of other applications outside of Stripe.
What the code does is it allows you to pass a three digit currency code to the function. It then looks to see if the currency code you passed to the function exists in the array of $currencies. If it does, it will return the HTML code for that currency symbol. If it does not, it will simply return the same three digit code you passed to the function.
You would use it like this:
$currency = 'usd'; $symbol = show_currency_symbol( $currency ); echo $symbol; // this would display $, which is output by the HTML code $
You will notice in the array that not all currencies have an HTML symbol available. I did some searching to find currency symbols for all of those currency codes, and when nothing turned up, I resorted to using the uppercase version of the three digit currency code. If I missed anything, please let me know so I can update the code.
Why not just hard code a currency symbol?
When you are creating a plugin that can be used by someone anywhere in the world, you can’t predict what currency the plugin will ultimately need to return. Sure it’s easy enough to slap a Dollar sign next to the numeric output, but what if someone in England needs the Pound symbol, or someone in India needs the Rupee symbol? This code will allow your plugin to dynamically display the correct symbol depending on your user’s needs.