Page 1 of 1

[SOLVED]Adding leading zeros to an array created using range

Posted: Mon Feb 05, 2007 9:04 am
by impulse()
I've just created an array of minutes in an hour using the range function:

Code: Select all

$minutes = range(0,59);
But the output shows:

0
1
2
3
4
5
6
7
8
9
10
11 etc

How is this possible to change to:

00
01
02
03
04
05
06
07
08
09
10
11 etc?

Without creating another loop to replace all values lower than 10?

At the moment I have the following code:

Code: Select all

$minute       = array(00,01,02,03,04,05,06,07,08,09);
for ($i = 10; $i < 60; $i++) {
  array_push($minute, $i);
}


Regards,

Posted: Mon Feb 05, 2007 9:16 am
by feyd
Without being in strings, a leading zero tells PHP to parse the numbers as octal. 08 and 09 will result in zeros.

Use sprintf() during output.

Posted: Mon Feb 05, 2007 9:18 am
by onion2k
Why do you need them in the array? I'd put them into the array as integers so all the maths I do with them works properly, and then display them on the front end using str_pad() or sprintf() or ((strlen($x)<2)?"0".$x:$x) or something.

Posted: Mon Feb 05, 2007 9:26 am
by impulse()
Sprintf sorted the problem using the following:

Code: Select all

sprintf("%02d", $var);
The reason they're in an array it to make it simple for me to do

Code: Select all

range(0,59)
and I have the numbers I need, easily. I'm then using a foreach loop and created a dropdown box.

Posted: Mon Feb 05, 2007 9:39 am
by feyd
A for() loop would be more straight forward and use less memory.

Posted: Mon Feb 05, 2007 6:49 pm
by visitor-Q
did no one think of this?

Code: Select all

<?php
        $minutes = range(0, 59);

        foreach($minutes as $minute){
                (($minute < 10) ? ($minute = 0 . $minute));
                echo $minute ."<br />\n";
         }
?>
is it not the same? is it better, or worse?

Posted: Tue Feb 06, 2007 4:04 am
by onion2k
visitor-Q wrote:is it better, or worse?
It doesn't work, so I guess that makes it worse.

Posted: Tue Feb 06, 2007 9:25 am
by visitor-Q
onion2k wrote:
visitor-Q wrote:is it better, or worse?
It doesn't work, so I guess that makes it worse.
sorry, most of my code is untested, and mainly for a theoretical example. this works...

Code: Select all

<?php
        $minutes = range(0, 59);

        foreach($minutes as $minute){
                (($minute < 10) ? ($minute = 0 . $minute) : ('')); //forgot that last bit on this line
                echo $minute ."<br />\n";
         }
?>