2

How to make a number 8 digit as standard digit. The number will be get to a user id from database. Example

user_id = 1 // This should should be echo as 00000001
user_id = 11 // This should should be echo as 00000011
user_id = 111 // This should should be echo as 00000111

How can I code this? Please help thanks.

6 Answers 6

2

You can use printf function with %08s as the format string:

printf("%08s",$user_id);

If you want to store the result back in the string you can use sprintf as:

$user_id = sprintf("%08s",$user_id);

The format specifier %08s says:

s : Interpret the argument as a string
8 : Print the string left justified within 8 alloted places
0 : Fill the unused places with 0
Sign up to request clarification or add additional context in comments.

Comments

2

You could use printf:

printf("%08d", $user_id);

Comments

2

PHP has sprintf:

$user_str = sprintf("%08d", $user_id);
echo $user_str;

Comments

2

You can do with str_pad

   echo str_pad($user_id,8,'0',STR_PAD_LEFT);

Comments

0

$user_id = str_pad($user_id, 8, "0", STR_PAD_LEFT);

Comments

0
function leadingZeroes($number, $paddingPlaces = 3) {
    return sprintf('%0' . $paddingPlaces . 'd', $number);
}

Source.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.