How can you add leading zeros to a number in PHP to ensure it always has a specific length?

When dealing with numbers in PHP, if you need to ensure that a number always has a specific length by adding leading zeros, you can achieve this by using the str_pad() function. This function allows you to pad a string to a specific length with another string, in this case, zeros. By specifying the desired length and the character to pad with, you can ensure that the number always has the required length.

$number = 123;
$desired_length = 5;
$number_with_zeros = str_pad($number, $desired_length, '0', STR_PAD_LEFT);

echo $number_with_zeros; // Outputs "00123"