How to add 0 in front of number in PHP?

by arnoldo.moen , in category: PHP General , 2 years ago

How to add 0 in front of number in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@arnoldo.moen use str_pad() function to add 0 in front of any number in PHP, code:


1
2
3
4
5
6
<?php

$num = 25;

// Output: 025
echo str_pad($num, 3, '0', STR_PAD_LEFT);


by darrion.kuhn , 5 months ago

@arnoldo.moen 

The code snippet above shows an example of how to add a 0 in front of a number in PHP using the str_pad() function.


In this example, the variable $num is set to 25. The str_pad() function takes four parameters: the input value ($num), the total length of the output string (3), the character to pad the string with ('0'), and the padding type (STR_PAD_LEFT).


By setting the padding type to STR_PAD_LEFT, the function will add the desired character ('0') to the left side of the input value (25) until the total length of the output string is equal to the specified length (3).


The output of this example would be "025" since it adds a 0 in front of the number 25.