开发者

Leading zeroes in 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){      
        sp开发者_如何学编程rintf("%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...


Use str_pad:

for($i=0; $i<60; $i++){
    str_pad($i, 2, "0", STR_PAD_LEFT)
}


I like the offered solutions, but I wanted to do it without deliberate for/foreach loops. So, here are three solutions (subtle variations):

Using array_map() with a designed callback function

$array = array_map(custom_sprintf, range(0,59));
//print_r($array);

function custom_sprintf($s) {
    return sprintf("%02d", $s);
}

Using array_walk() with an inline create_function() call

$array = range(0,59);
array_walk($array, create_function('&$v', '$v = sprintf("%02d", $v);'));
// print_r($array);

Using array_map() and create_function() for a little code golf magic

$array = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(0,59));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜