Jump to content

001 + 1 = 2


johnb41

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...