How do I strip the last pipe out of the list of numbers that is generated?
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
echo "|";
}
How do I strip the last pipe out of the list of numbers that is generated?
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
echo "|";
}
|
before$s = '';
foreach ($days as $day) {
if ($s) $s .= '|';
$s .= strtoupper($day->format('d')+543);
}
echo $s;
|
only if not last item$n = iterator_count($days);
foreach ($days as $i => $day) {
echo strtoupper($day->format('d')+543);
if (($i+1) != $n) echo '|';
}
$s = array();
foreach ($days as $day) {
$s[] = strtoupper($day->format('d')+543);
}
echo implode('|', $s);
|
(or rtrim
it)$s = '';
foreach ($days as $day) {
$s .= strtoupper($day->format('d')+543) . '|';
}
echo substr($s, 0, -1);
# echo rtrim($s, '|');
collect output in the loop, and add |
before, not after.
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
$echo = '';
foreach ($days as $day) {
if ($echo!='') $echo.='|';
$echo.=strtoupper($day->format('d')+543);
}
echo $echo;
570|571|572|573|544|545|546
You can't do this as the code is written because:
A very easy way to achieve the result you want is
echo implode('|', array_map(function($d) { return $d->format('d')+543; },
iterator_to_array($days)));
This works by converting the iteration of $days
into an array, formatting the results with array_map
and gluing them together with a standard implode
.
Cut last char:
echo substr($str,0,-1);
EXAMPLE
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
$str .= strtoupper($day->format('d')+543);
$str .= "|";
}
echo substr($str,0,-1);
Try like
$cnt = count($days);
$i = 0;
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
if($i++ < $cnt)
echo "|";
}
You can use output buffering to control what is echo'ed.
http://md1.php.net/manual/en/function.ob-start.php
Or the implode solution.