从foreach循环中剥离最后一个字符 [英] Stripping last character from a foreach loop

查看:132
本文介绍了从foreach循环中剥离最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从生成的数字列表中删除最后一个管道?

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


推荐答案

1。 Concat to string,但在

之前添加 |

1. Concat to string but add | before

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



2。回音 | 只有最后一个项目



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。加载到数组,然后打开



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 | (或 rtrim it)



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

这篇关于从foreach循环中剥离最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆