I'm doing a for loop to count from 0001 up to 0999
How can i do this with php. All i've got so far is a normal php for loop.
I'm doing a for loop to count from 0001 up to 0999
How can i do this with php. All i've got so far is a normal php for loop.
Something like this?
for($i = 1; $i<=999; $i++){
echo str_pad($i, 4, '0', STR_PAD_LEFT);
}
Additionally, you can make use of sprintf()
instead of str_pad()
, but I think str_pad()
looks much clearer than sprintf()
in this case.
What you want to do is a normal loop and format the output:
for( $i=1; $i<=999; $i++) {
$myformat = str_pad($i, 4, '0', STR_PAD_LEFT);
// do something with $myformat
}
Try that code:
for($n=1;$n<=999;$n++)
{
$formatted_n = str_pad($n, 4, '0', STR_PAD_LEFT);
// add some code here
}
<?php
for($i=1; $i<=999; $i++) {
echo str_pad($i, 4, "0", STR_PAD_LEFT);
}
?>
Here is a version using sprintf()
:
foreach (range(1, 999) as $i){
echo sprintf("%04d", $i);
} // output: 000100020003...