php - Generating a number based on post ID

admin2025-04-26  4

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745652531a312256.html

最新回复(0)