money_format()
The money_format() function formats a number as a currency string. Note: This function was removed in PHP 7.0. For modern PHP, use the NumberFormatter class from the intl extension. Below is the historical syntax and usage for legacy codebases.
The syntax is as follows:
PHP syntax of money_format()
string money_format ( string $format , float $number )The function takes two parameters: $format (a string containing formatting rules) and $number (the numeric value to format). Common format specifiers include:
%i– International currency format (e.g.,USD,EUR)%n– Local currency format (e.g.,$,€)
Here is an example of how to use the money_format() function:
Example of PHP money_format()
<?php
$number = 1234.56;
setlocale(LC_MONETARY, 'en_US');
echo money_format('%n', $number);
?>In this example, $number holds a floating-point value. The setlocale() call configures the monetary locale to en_US. Note that setlocale() returns false if the specified locale is not supported, which would cause money_format() to fail. Additionally, setlocale() is deprecated in PHP 8.1 and removed in PHP 8.2, so this example only runs in PHP 7.4 and earlier.
The output of this code will be:
$1,234.56This function was historically used for accounting and financial formatting in PHP. For current projects, the NumberFormatter class provides locale-aware formatting and is the recommended approach.
This overview covers the legacy money_format() function for reference and maintenance of older PHP code.
Practice
What does the 'money_format' function in PHP do?