Youssef
Youssef

Reputation: 474

how to convert int to string with fixed length

I need a function that will be convert an int value to string with fixed length.

For example :

5 -> '000005', 5245 -> '005245' ..

If the number is bigger than 999999 it stays as it is:

2548562 -> '2548562'

Is there PHP function to do that, or do I need to create a custom function?

Upvotes: 0

Views: 2302

Answers (2)

Martin Navarro
Martin Navarro

Reputation: 624

What you want is this

$value = str_pad($value, 6, '0', STR_PAD_LEFT);

This will pad your integer value with 0's as a string. If there are more than 6 digits, the integer will simply stay as is.

Example:

<?php

$value = 5;

$value = str_pad($value, 6, '0', STR_PAD_LEFT);

print($value . "\xA");

$value = 2548562;

$value = str_pad($value, 6, '0', STR_PAD_LEFT);

print($value);

?>

Output:

000005
2548562

Upvotes: 2

Mohammad
Mohammad

Reputation: 737

You can use this

$resultString = str_pad($value, length , '0' , STR_PAD_LEFT);

Upvotes: 0

Related Questions