generate array from php while loop

38,371

Solution 1

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>";
}

Solution 2

$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.

Solution 3

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.

Share:
38,371
grantiago
Author by

grantiago

cut and paste php hack

Updated on February 02, 2020

Comments

  • grantiago
    grantiago over 4 years

    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.