PHP从我的循环中删除最后一个字符

时间:2013-07-03 21:39:44

标签: php html forms

我正在从我的表单中写一个字符串,我想从最后删除最后一个逗号。我知道我可以使用rtrim(),但我不明白如何从循环中返回变量。我确信这是一个简单的答案,只是非常困惑。谢谢!

if (isset($_POST['submit'])) {

foreach ( $_POST['data'] as $data )
{

    echo $data['Monday'];
    echo $data['Tuesday'];
    echo $data['Wednesday'];
    echo $data['Thursday'];
    echo $data['Friday'];
    echo $data['Saturday'];
    echo $data['Sunday'];
    echo ", ";
}

} // end if

4 个答案:

答案 0 :(得分:3)

您可以检查您是否在最后一个元素上并跳过逗号(如果是这样):

end($_POST['data');             // fast forward to the end of the array
$lastKey = key($_POST['data');  // and remember what the last key is

foreach ( $_POST['data'] as $key => $data )
{
    echo $data['Monday'];
    echo $data['Tuesday'];
    echo $data['Wednesday'];
    echo $data['Thursday'];
    echo $data['Friday'];
    echo $data['Saturday'];
    echo $data['Sunday'];
    if ($key !== $lastKey) echo ", ";
}

这种方法对我来说感觉更清洁:预防胜于治疗。

答案 1 :(得分:1)

不是立即回显数据,而是将其存储在缓冲区中......

if (isset($_POST['submit'])) {
  $buffer = "";
  foreach ( $_POST['data'] as $data )
  {
      $buffer .= $data['Monday'];
      $buffer .= $data['Tuesday'];
      $buffer .= $data['Wednesday'];
      $buffer .= $data['Thursday'];
      $buffer .= $data['Friday'];
      $buffer .= $data['Saturday'];
      $buffer .=  $data['Sunday'];
      $buffer .= ", ";
  }
  $buffer = rtrim($buffer, ", ");
  echo $buffer;
} // end if

或者,甚至更短:

if (isset($_POST['submit'])) {
  implode(", ", $data);
} // end if

假设$data只有那些星期一到星期日的密钥..

答案 2 :(得分:1)

你需要一个变量

$str = null;
if (isset($_POST['submit'])) {

    foreach ( $_POST['data'] as $data )
    {

        $str .= $data['Monday'] .
        $data['Tuesday'] .
        $data['Wednesday'] .
        $data['Thursday'] .
        $data['Friday'] .
        $data['Saturday'] . 
        $data['Sunday'] . 
        ", ";

    }
$str = substr($str,0,-2);
}

然后你有$str中的数据,然后你可以回复或用

做事

答案 3 :(得分:1)

您可以获取$_POST['data']的最后一个索引,并且只有在达到时才会回显,

end($_POST['data']);
$last_key = key($_POST['data']);
foreach ($_POST['data'] as $key => $data) {
    // echoes here
    if ($key != $last_key) {
        echo ',';
    }
}