I would like to present a list from 0 to 59 with the numbers 0 to 9 having a leading zero. This is my code, but it doesn't work so far. What is the solution?
for ($i=0; $i<60; $i++){
if ($i< 10){
sprintf("%0d",$i);
}
array_push($this->minutes, $i);
}
Using %02d
is much shorter and will pad the string only when necessary:
for($i=0; $i<60; $i++){
array_push($this->minutes,sprintf("%02d",$i));
}
You are not assigning the result of sprintf
to any variable.
Try
$padded = sprintf("%0d", $i);
array_push($this->minutes, $padded);
Note that sprintf does not do anything to $i
. It just generates a string using $i
but does not modify it.
EDIT: also, if you use %02d
you do not need the if
Try this...
for ($i = 0; $i < 60; $i++) {
if ($i < 10) {
array_push($this->minutes, sprintf("%0d", $i));
}
array_push($this->minutes, $i);
}
You are ignoring the returned value of sprintf, instead of pushing it into your array...
important: The method you are using will result in some items in your array being strings, and some being integers. This might not matter, but might bite you on the arse if you are not expecting it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With