Вопрос

I'm generating the current day and the next upcoming six with this:

 <?php
     for($i=0; $i<=6; $i++){
         echo strtoupper(date("j",mktime(0, 0, 0, 0,date("d")+$i,0))."\n");
         echo "|";
     }  
 ?>

Which produces this (on February 8 when I'm writing this):

8 |9 |10 |11 |12 |13 |14 |

How do I do the following:

  • Get rid of the space after each numeral
  • Get rid of the trailing pipe

The output I'd like would be:

8|9|10|11|12|13|14
Это было полезно?

Решение

This task is ideal for a do..while loop:

$i = 0;
do {
    echo strtoupper(date("j",mktime(0, 0, 0, 0,date("d")+$i,0)));
} while ($i++ < 6 && print "|");

The space is present because you had \n in your output. Any whitespace will be made into a space by your browser.

Другие советы

Just for fun with DateTime classes (PHP 5.3+)

<?php
$start = new DateTime();
$interval = new DateInterval('P1D');
$period = new DatePeriod($start,$interval,6);

$days = array();
foreach($period as $date) {
  $days[] = $date->format('d');
}

$daysString = implode('|',$days);

echo $daysString;

Yeah... DatePeriod needs to implement some kind of interator to be useful...

You could use a variable and append to it for the text, and output the string after your for loop.

$output = '';
for($i=0; $i<=6; $i++){
    $output .= (date("j",mktime(0, 0, 0, 0,date("d")+$i,0))).'|';
}
$output = rtrim($output, '|');
echo $output;
for($i=0; $i<=6; $i++){
$dates[] = date('j', strtotime('+ '.($i+1).' days');
}
echo implode('|', $dates);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top