Jump to content

001 + 1 = 2


johnb41
 Share

Recommended Posts

My script needs a variable number to start at 001, and when you add 1 to it, it needs to be 002, 003, etc. Currently if you add 1 to 001, the result is 2.Whatever I try, PHP removes the leading zero's and then adds the numbers.Is there anyway to keep the number always 3 digits? (assuming it's less than 1000)Thanks!John

Link to comment
Share on other sites

You could use str_pad():

function pad($n) {	if ($n > 1000) return $n;	return str_pad($n, 3 - strlen($n), "0", STR_PAD_LEFT);}$n = 1;$n = pad($n + 1);echo $n; //echoes 001

Link to comment
Share on other sites

You could use str_pad():
function pad($n) {	if ($n > 1000) return $n;	return str_pad($n, 3 - strlen($n), "0", STR_PAD_LEFT);}$n = 1;$n = pad($n + 1);echo $n; //echoes 001

Thanks so much!! FYI, for me, the second parameter should just be "3", not 3-strlen($n).John
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...