0

so i got this script for the moment :

<select class="n-select" name="heure-event" id="heure-event">
    <option selected="selected"></option>
    <?php
        for ( $heures = 0 ; $heures <= 23 ; $heures++ ){
            for ( $minutes = 0 ; $minutes <= 45 ; $minutes += 15 ){ 
    ?>
    <option value="<?php echo $heures.':'.$minutes;?>:00">
        <?php
            echo $heures.':'.$minutes;
        ?>
    </option>   
    <?php
            }
        }
    ?>                    
</select>

It works very well, but the little problem : 1:15, 1:0, etc.

I want: 01:15 and 1:00.

Can somebody help me? I need probably to check if $i is < 10 then add '0.$i' or something like this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Peter
  • 1,719
  • 4
  • 22
  • 31
  • 2
    Take a look to http://php.net/manual/es/function.sprintf.php it returns a formatted string – Lobo Sep 04 '12 at 15:41

4 Answers4

5

Use strftime

<?php

$hour = 1;
$minute = 9;

echo strftime('%H:%M', mktime($hour, $minute)); // 01:09
Alexei
  • 672
  • 1
  • 5
  • 13
3

That's just a display problem. Don't store 'formatted' data, especially when it's numeric.

So... for the value, store 1:15, but display 01:15, via

value="<?php echo "$heure:$minutes" ?>"><?php echo sprintf('%02d:%02d', $heures, $minutes) ?></option>

sprintf()

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. Specifically: `printf('', $heures, $minutes);` – mickmackusa Apr 09 '22 at 00:20
0
                                <option value="<?php echo sprintf('%02d:%02d', $heures, $minutes) ?>:00"><?php echo sprintf('%02d:%02d', $heures, $minutes) ?></option>
Peter
  • 1,719
  • 4
  • 22
  • 31
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. Specifically: `printf('', $heures, $minutes);` – mickmackusa Apr 09 '22 at 00:18
-3
$days = array('' => '');
for ($i = 1; $i <= 31; $i++)
{
    $days[$i] = $i;
}

$months = array('' => '');
for ($i = 1; $i <= 12; $i++)
{
    $months[$i] = $i;
}

$hours = array('' => '');
for ($i = 9; $i <= 18; $i++)
{
    $hours[$i] = sprintf('%02d', $i);
}

$mins = array('' => '');
for ($i = 0; $i <= 45; $i += 15)
{
    $mins[$i] = sprintf('%02d', $i);
}

$years = array(2012 => 2012, 2013 => 2013);

Edit: Woops, completely misread the question, apologies. Simply use sprintf to format the numbers correctly:

$heures = sprintf('%02d', $heures);
$minutes= sprintf('%02d', $minutes);
<option value="<?php echo $heures.':'.$minutes;?>:00"><?php echo $heures.':'.$minutes;?></option>
Matt Humphrey
  • 1,554
  • 1
  • 12
  • 30