最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - Generating a number based on post ID

matteradmin6PV0评论

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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far