How can I increase 0000 by 1 and keep formatting?

$i=0000; while($i<=1231) { print "$i"; $i++; } 

I want it to display 0001 , 0002 0003 0004 but instead it prints: 0 1 , 2

Does anyone know why this is not working?
Thank you in advance.

+4
source share
5 answers

Try using printf("%04s",$i);

+10
source
 print str_pad($i,4,'0',STR_PAD_LEFT); 

- this is only one way ... you can also use sprintf .

+4
source

PHP treats the string 0000 as the number 0 when considering the increment. The increment operator ++ can also work with regular strings, but due to processing such as PHP it does not work, as you would expect in this case. However, if you started with a string like a0000 , then incrementing it will result in a0001 . For instance:

 <?php $var = 'a0000'; for ($i = 0; $i < 100; $i++) { $var++; } echo $var; // Outputs a0100 ?> 

Although, since this method of using the increment operator is a little unorthodox, I would recommend using printf("%04d", $var) (or sprtinf() ) in this case instead of the output. For instance:

 <?php $var = 0; for ($i = 0; $i < 100; $i++) { printf('%04d ', $var); $var++; } ?> 
+3
source

sprintf (), str_pad ()

+1
source

try $x = str_pad($z + 1, 5, 0, STR_PAD_LEFT);

+1
source

Source: https://habr.com/ru/post/1307256/


All Articles