I want to run a while(or any) loop to output a small list of dates as an array
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
while($day < $end)
{
echo date('d-M-Y', $day) .'<br />';
$day = strtotime("+1 day", $day) ;
}
This works fine for printing, but I want to save it as an array (and insert it in a mysql db). Yes! I don't know what I'm doing.
Show activity on this post. I would like to store value from while loop but not in multidimensional way : $movies_id = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $id = $row['id']; $title_id = $row['title_id']; $movies_id[] = [$id => $title_id]; } print_r($movies_id);
The PHP foreach LoopThe foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value. The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break.
to create a array, you need to first initialize it outside your loop (because of variable scoping)
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$dates = array(); //added
while($day < $end)
{
$dates[] = date('d-M-Y', $day); // modified
$day = strtotime("+1 day", $day) ;
}
echo "<pre>";
var_dump($dates);
echo "</pre>";
you can then use your dates using either foreach
or while
foreach approach :
foreach($dates as $date){
echo $date."<br>";
}
while approach :
$max = count($dates);
$i = 0;
while($i < $max){
echo $dates[$i]."<br>";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With