我遇到过很多次这样的情况
$str = '';
foreach($arr as $item)
{
$str .= $item . ',';
}
结果会是类似$str = item1,item2,item3,
的东西。但我不希望,
在最后。
现在有一些方法可以去除,
。
例如
- 使用
substr()
切断,
。 编写一个函数来检测最后一项并将循环体更改为
$str .= $item; if(!last($item)) $str .= ',';
我认为这是很好的可读性,但是程序检查每一个项目,如果它是最后一个,这显然是只有一次的情况。
- 使用
implode(',', $arr)
(但是让我们假设这是不可能的。考虑一个更复杂的循环体)
处理foreach循环中的最后(或第一个)项的最佳实践是什么?
在没有join
类方法的语言中,这是我使用(并且看到使用)一段时间的方法。
result = ""
delim = ""
foreach(string in array)
result += delim + string
delim = ","
(适用于您喜欢的语言)
在使用PHP的情况下,它看起来像
$str = "";
$delim = "";
foreach($arr as $item) {
$str .= $delim + $item;
$delim = ",";
}
跟随这个例子,它可能会解决你的障碍。
$arr = array(1,2,3,4,5,6,7);
$copy = $arr;
foreach ($arr as $val) {
echo $val;
if (next($copy )) {
echo ','; // Add comma for all elements instead of last
}
}
您还可以使用rtrim
来删除最后一个不需要的字符
$str = rtrim($str, ',');
这也可能是一种方法:
$last = end($arr); // returns the last item and sets the internal pointer to the end
unset($arr[key($arr)]) // deletes the last item from the array
$str = '';
foreach($arr as $item)
{
$str .= $item . ',';
}
$str .= $last;
这不会在循环中检查或分配任何额外的东西,但我认为这不是一个好的可读方式。