Reputation: 175
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.
Upvotes: 5
Views: 45949
Reputation: 1856
The simple way is just:
$start = $day = strtotime("-1 day");
$end = strtotime('+6 day');
$arr = array();
while($day < $end)
{
$arr[] = date('d-M-Y', $day);
$day = strtotime("+1 day", $day) ;
}
// Do stuff with $arr
the $arr[] = $var
is the syntax for appending to an array in PHP. Arrays in php do not have a fixed size and therefore can be appended to easily.
Upvotes: 2
Reputation: 865
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>";
}
Upvotes: 11
Reputation: 324790
$arr = Array();
while(...) {
$arr[] = "next element";
...
}
The []
adds a new element to an array, just like push()
but without the overhead of calling a function.
Upvotes: 5