Pravin Vavadiya Pravin Vavadiya - 7 days ago 6
PHP Question

Use static keyword in a for loop?

I want to use the

static
keyword in my for loop.

Is it possible? if yes then how?

Here is my code:

$current_time = date('h:i A');
<select>

for($i = 0; $i <= 5; $i++) {
if ($i=0) {
echo "<option>" . date("h:i A", $current_time) . "</option>";
}else{
static $tNow = strtotime("+15 minutes",strtotime($current_time));
echo "<option>" . date("h:i A", $tNow) . "</option>";
}
}
<select>


When I'm using the
static
keyword, I'm getting a php error.

I want to display a
<select>
element with each option being 15 minutes steps, like
12:00
,
12:15
,
12:30
.

Answer

I don't know why you want to use static keyword in your code, but as suggested you should read here: http://php.net/manual/en/language.oop5.static.php, how and when to use static keyword.
If your goal is to display dropdown and getting option value different 15mint time like this 12:00, 12:15, 12:30..... this is my solution:

$current_time[0] = date('h:i A');
echo"<select>";
echo "<option>" . $current_time[0] . "</option>";
$step=0;
for($i = 1; $i <=5; $i++) {
    $step=$step+15;
    $current_time[$i] = strtotime("+".$step." minutes", strtotime($current_time[0]));
    echo "<option>" . date("h:i A", $current_time[$i]) . "</option>";
}

echo"</select>";
var_dump($current_time);

Working code here: http://ideone.com/zM0eue

Explanation: I used an array to contain all strtotime output in for loop. Each time I used the same $current_time[0] to calculate new $current_time[$i] with a $step variable incremented by +15 each time.

Comments