最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Generating a number based on post ID

programmeradmin8浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论