$caseid
is (usually) a 5-digit number (it could be lower). I want a leading 0 so that the number is 6 digits long:
<?php
$caseid=12345;
echo str_pad(strval($caseid), 6-strlen(strval($caseid)), '0', STR_PAD_LEFT); ?>
This doesn't work as expected (displays the same number). Instead if I add 5 to the second argument of str_pad
, it works.
<?php echo str_pad(strval($caseid), 11-strlen(strval($caseid)), '0', STR_PAD_LEFT); ?>
It works. What is the error here?
你不需要计算你想要它的总字符数的差异。
str_pad(strval($caseid), 6, '0', STR_PAD_LEFT);
I was once bothered by str_pad()
s behavior too. I got tired of it, and returned to old stable sprintf()
.
<?php
header('Content-Type: text/plain');
$test = [
1,
12,
123,
1234,
12345,
123456
];
foreach($test as $n){
echo sprintf('%06d' . PHP_EOL, $n);
}
?>
Result:
000001
000012
000123
001234
012345
123456
Maybe, it is not an answer, but I hope it might help somebody.
See the function prototype:
string str_pad (
string $input ,
int $pad_length
[, string $pad_string = " "
[, int $pad_type = STR_PAD_RIGHT ]]
)
Pad a string to a certain length with another string
, $pad_length means the length you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.