3

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 "|";
}
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
portnoy-the-elder
  • 141
  • 1
  • 2
  • 9

6 Answers6

5

1. Concat to string but add | before

$s = '';
foreach ($days as $day) { 
    if ($s) $s .= '|';
    $s .= strtoupper($day->format('d')+543); 
}
echo $s;

2. Echo | 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 '|';
}

3. Load to array and then implode

$s = array();
foreach ($days as $day) { 
    $s[] = strtoupper($day->format('d')+543); 
}
echo implode('|', $s);

4. Concat to string then cut last | (or rtrim it)

$s = '';
foreach ($days as $day) { 
    $s .= strtoupper($day->format('d')+543) . '|';
}
echo substr($s, 0, -1);
# echo rtrim($s, '|');
Glavić
  • 42,781
  • 13
  • 77
  • 107
3

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
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
3

You can't do this as the code is written because:

  1. You don't know how many iterations there will be and
  2. You are directly echoing the strings (so you cannot post-process the output)

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

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);
Adam
  • 1,371
  • 2
  • 11
  • 12
0

Try like

$cnt = count($days);
$i = 0;
foreach ($days as $day) { 
    echo strtoupper($day->format('d')+543); 
        if($i++ < $cnt)
            echo "|";
 }
GautamD31
  • 28,552
  • 10
  • 64
  • 85
-1

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.

Katran
  • 86
  • 1
  • 2