What are some best practices for handling currency-formatted numbers in PHP when sorting arrays?
When sorting arrays containing currency-formatted numbers in PHP, it's important to convert the currency strings to numbers for accurate sorting. One way to achieve this is by removing any non-numeric characters and converting the strings to floats before sorting the array.
// Sample array containing currency-formatted numbers
$numbers = ['$10.50', '$5.75', '$20.00', '$3.25'];
// Remove non-numeric characters and convert to float
$numeric_numbers = array_map(function($num) {
return (float) preg_replace('/[^0-9.]/', '', $num);
}, $numbers);
// Sort the array
asort($numeric_numbers);
// Output the sorted array
print_r($numeric_numbers);