将foreach循环的输出存储到变量中

时间:2015-09-29 04:44:13

标签: php foreach

我有一个foreach循环,它将回显用户从复选框中做出的所有选择。

我正在尝试将值存储到名为$getCentralArea的变量中。但是,当我回显$getCentralArea时,它显示4 - 仅显示所选复选框的最后一个值。我应该得到的正确值是1,2,3,4

if(!empty($_POST['centralArea'])) 
{
    foreach($_POST['centralArea'] as $centralArea) 
    {
        $getCentralValue = $centralArea.","; //Output will be in the following format 1,2,3,4
    }
}else{ $getCentralArea="";}

4 个答案:

答案 0 :(得分:1)

你可以连接但是留下一个逗号。此外,无需循环,只需implode()数组:

$getCentralValue = implode(',', $_POST['centralArea']);

答案 1 :(得分:0)

您需要使用$centralArea(或$getCentralValue)运算符将..=连接起来,否则每次都会覆盖$getCentralValue循环:

if(!empty($_POST['centralArea'])) 
{
    foreach($_POST['centralArea'] as $centralArea) 
    {
        $getCentralValue .= $centralArea.","; //Output will be in the following format 1,2,3,4
    }
    $getCentralValue = rtrim($getCentralValue, ",");
} else{ $getCentralArea=""; }

答案 2 :(得分:0)

尝试这样:使用内爆。

或者

$result=implode(",",$_POST['centralArea']);//Output will be in the following format 1,2,3,4

或者如果您不希望直接使用帖子变量。

      $getCentralValue=array();
        foreach($_POST['centralArea'] as $centralArea) 
        {
            $getCentralValue[]= $centralArea; 
        }

        $result=implode(",",$getCentralValue);//Output will be in the following format 1,2,3,4

    echo $result;

答案 3 :(得分:0)

我宁愿将它们推入数组,然后使用implode打印它们

if(!empty($_POST['centralArea'])) 
            {
              $stack = array();
                foreach($_POST['centralArea'] as $centralArea) 
                {
                    array_push($stack,$centralArea);
               }
//print in 1,2,3,4
$comma_separated = implode(",", $stack);

echo $comma_separated;

            }