How can PHP be used to format numerical values with leading zeros for proper sorting?

When sorting numerical values as strings in PHP, it is important to ensure that numbers with leading zeros are formatted correctly to maintain the desired order. One way to achieve this is by using the str_pad() function to add leading zeros to the numbers before sorting them as strings.

$numbers = array("002", "01", "2", "0030", "20");

// Add leading zeros to each number
foreach ($numbers as &$number) {
    $number = str_pad($number, strlen(max($numbers)), "0", STR_PAD_LEFT);
}

// Sort the numbers
sort($numbers);

// Output the sorted numbers
foreach ($numbers as $number) {
    echo $number . "<br>";
}