Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate array from php while loop

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.

like image 624
grantiago Avatar asked Feb 02 '12 00:02

grantiago


People also ask

How can we store values from while loop into an array in PHP?

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);

Can we use for loop for array in PHP?

The PHP foreach LoopThe foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

How can I print 1 to 10 numbers in PHP?

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.


1 Answers

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>";
}
like image 184
Bogdan Avatar answered Sep 23 '22 19:09

Bogdan