sanders
sanders

Reputation: 10898

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){      
        sprintf("%0d",$i);
    }
    array_push($this->minutes, $i);
}

Upvotes: 5

Views: 3912

Answers (5)

Rik Heywood
Rik Heywood

Reputation: 13972

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

Upvotes: 3

Steve McLenithan
Steve McLenithan

Reputation: 293

Use str_pad:

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

Upvotes: 2

allnightgrocery
allnightgrocery

Reputation: 1380

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));

Upvotes: 1

Pekka
Pekka

Reputation: 449843

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));
}

Upvotes: 14

nico
nico

Reputation: 51690

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

Upvotes: 4

Related Questions