php - Generating a number based on post ID

I am trying to generate a number that will be 5 digits including the post ID. For example: if post ID is 25, the number

I am trying to generate a number that will be 5 digits including the post ID. For example: if post ID is 25, the number will be 00025.

So far my codes are below. It's working but is there any better way to lessen the code line? more dynamic?

$post_id = get_the_ID();
$postidlength = strlen($post_id);
if($postidlength = 1){
    $zero="0000";
}

elseif($postidlength = 2){
    $zero="000";
}
elseif($postidlength = 3){
    $zero="00";
}
elseif($postidlength = 4){
    $zero="0";
}
else{
    echo "invalid id";
} 


$result = $zero.$post_id;
echo $result;

I am trying to generate a number that will be 5 digits including the post ID. For example: if post ID is 25, the number will be 00025.

So far my codes are below. It's working but is there any better way to lessen the code line? more dynamic?

$post_id = get_the_ID();
$postidlength = strlen($post_id);
if($postidlength = 1){
    $zero="0000";
}

elseif($postidlength = 2){
    $zero="000";
}
elseif($postidlength = 3){
    $zero="00";
}
elseif($postidlength = 4){
    $zero="0";
}
else{
    echo "invalid id";
} 


$result = $zero.$post_id;
echo $result;
Share Improve this question edited Mar 27, 2019 at 22:05 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Mar 27, 2019 at 20:47 NoobieNoobie 1091 gold badge2 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

str_pad is the function you're looking for.

echo str_pad( get_the_ID(), 5, "0", STR_PAD_LEFT);

This should do the trick.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745652530a4638349.html

相关推荐

  • php - Generating a number based on post ID

    I am trying to generate a number that will be 5 digits including the post ID. For example: if post ID is 25, the number

    22天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信