tags:

views:

186

answers:

5

Hello,

I would like to present a list from 0 to 59 of with the numbers 0 to 9 have a leading zero. This is my code but it doesn't work so far. Any idea's?

for($i=0; $i<60; $i++){
 if($i< 10){      
    sprintf("%0d",$i);
 }
   array_push($this->minutes,$i);
}
+3  A: 

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

nico
+8  A: 

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));
}
Pekka
+3  A: 

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

rikh
`%02d` solves the half number half string issue
nico
+1  A: 

http://php.net/manual/en/function.str-pad.php

for($i=0; $i<60; $i++){
    str_pad($i, 2, "0", STR_PAD_LEFT)
}
Steve McLenithan
+1 for answer I was about to post :)
Yacoby
A: 

I thought this was a great question so I wanted to throw my hat into the ring. I like the solutions proffered but wanted to do it without deliberate for/foreach loops. So, here's 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));
Inkspeak