我知道如何使用foreach遍历数组的项并附加一个逗号,但是去掉最后一个逗号总是很痛苦的。有没有一种简单的PHP方法可以做到这一点?
$fruit = array('apple', 'banana', 'pear', 'grape');
最终我想
$result = "apple, banana, pear, grape"
发布于 2014-10-22 15:15:08
以and
结尾的结果:
$titleString = array('apple', 'banana', 'pear', 'grape');
$totalTitles = count($titleString);
if ($totalTitles>1) {
$titleString = implode(', ', array_slice($titleString, 0, $totalTitles-1)) . ' and ' . end($titleString);
} else {
$titleString = implode(', ', $titleString);
}
echo $titleString; // apple, banana, pear and grape
发布于 2014-02-05 22:46:46
与Lloyd的答案类似,但适用于任何大小的数组。
$missing = array();
$missing[] = 'name';
$missing[] = 'zipcode';
$missing[] = 'phone';
if( is_array($missing) && count($missing) > 0 )
{
$result = '';
$total = count($missing) - 1;
for($i = 0; $i <= $total; $i++)
{
if($i == $total && $total > 0)
$result .= "and ";
$result .= $missing[$i];
if($i < $total)
$result .= ", ";
}
echo 'You need to provide your '.$result.'.';
// Echos "You need to provide your name, zipcode, and phone."
}
发布于 2012-11-08 22:56:08
我更喜欢在FOR循环中使用IF语句来检查以确保当前迭代不是数组中的最后一个值。如果不是,请添加逗号
$fruit = array("apple", "banana", "pear", "grape");
for($i = 0; $i < count($fruit); $i++){
echo "$fruit[$i]";
if($i < (count($fruit) -1)){
echo ", ";
}
}
https://stackoverflow.com/questions/2435216
复制相似问题