将数组数据合并为一个变量

时间:2017-02-14 02:38:01

标签: php arrays

我有foreaching数组:

$arr = array(2,3,4);
$copy = $arr;
foreach ($arr as $val) {
    echo $val;
    if (next($copy )) {
        echo ','; // Add comma for all elements instead of last
    }
}

结果是:

  

2,3,4-

如何创建具有值的变量高于结果,因此它看起来像$var = '2,3,4'

2 个答案:

答案 0 :(得分:1)

 foreach ($arr as $val) {
     $copy += $val;
}

答案 1 :(得分:1)

使用implode():

$arr = [2,3,4];
$var = implode($arr, ',');
var_dump( $var );

输出:

  

string(5)" 2,3,4"