Input: 1234567 Output: 01234567 Input: 1234 Output: 00001234There are many ways to pad leading zeros in string format. But in the case of a string, the best way to solve the problem is - use the function sprintf, and also use the function substr() .
- function sprintf()
- substr() functin
Syntax:
sprintf (format, $variable) // Returns the variable formated according to the format provided.
- Example 1:This example uses the sprintf() function to display a number with leading zeros.
php
$var
= 1234567;
echo
sprintf (
’% 08d’
,
$var
);
?>
01234567
- Example 2: Inthis example uses the sprintf() function to display negative numbers with leading zeros.
php
$var1
= -10;
$var2
= 10;
echo
sprintf (
’% 04s’
,
$var1
).
""
;
echo
sprintf (
’% 04s’
,
$var2
);
?>
0-10 0010
In the above example, we tried to format the number as a string and messed up the negative. But this will not happen if we format the numbers using "% d" rather than "% s". - Example 3:
php
$var1
= -10;
$var2
= 10;
echo
sprintf (
’% 04d’
,
$var1
).
""
;
echo
sprintf (
’% 04d’
,
$var2
);
?>
-010 0010
Syntax:
substr (string $string, int $start, int $length) // Returns the portion of string that define at start and length of the parameter ...Example :
Php
$num
= 123;
$str_length
= 4;
// Left padding if number < $str_length
$str
=
substr
(
"0000 {$num}"
, -
$str_length
);
echo
sprintf (
$str
);
?>
Output:0123