Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading zeroes in PHP

Tags:

php

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);
}
like image 821
sanders Avatar asked Jun 06 '10 17:06

sanders


3 Answers

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));
}
like image 59
Pekka Avatar answered Nov 11 '22 16:11

Pekka


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

like image 32
nico Avatar answered Nov 11 '22 17:11

nico


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...

like image 29
Rik Heywood Avatar answered Nov 11 '22 18:11

Rik Heywood