从数组PHP

时间:2016-04-13 12:21:02

标签: php arrays foreach

我有一个填充了这些字符串的数组,例如:

"1", "2", "3", "4", "5";

我有一个foreach()循环,循环遍历这些项目。它输出所有项目。现在,它输出:

1, 2, 3, 4, 5

但我想输出这个:

1, 12, 123, 1234, 12345

我该怎么做?因为prev()函数仅适用于当前项之前的函数。

我的代码:

$array = array("1", "2", "3", "4", "5");
foreach ($array as $item){
    echo $item;
}

6 个答案:

答案 0 :(得分:6)

$include = "";
foreach($array as $item) {
    echo $include . $item;
    $include .= $item;
}

分隔符版本:

$string = "";
$include = "";
foreach($array as $item) {
    $string .= $include . $item . ", ";
    $include .= $item;
}
echo rtrim($string, ', \t\n');

答案 1 :(得分:2)

每次连接当前项目:

$output = '';
foreach ($array as $item){
    $output .= $item;
    echo $output;
}

对于以逗号分隔的列表,您可以创建一个数组并进行内爆:

$items = '';
foreach ($array as $item){
    $items .= $item;
    $output[] = $items;
}
echo implode(', ', $output);

答案 2 :(得分:1)

php中的连接由。(点)

执行
$array = array("1", "2", "3", "4", "5");
$temp = '';
$output = '';
foreach ($array as $item){
    $temp .= $item;
    $output .= $temp . ',';
}
echo rtrim($output,',');

答案 3 :(得分:1)

$array = array("1", "2", "3", "4", "5");
$value = '';

foreach ($array as $item){
    $value .= $item;
    echo $value;
}

答案 4 :(得分:0)

$array = array("1", "2", "3", "4", "5");
$concatItem = "";
foreach ($array as $item){
    $concatItem = $concatItem.$item;
    echo $concatItem;
}

答案 5 :(得分:0)

像这样使用......

<?php

$array = array("1", "2", "3", "4", "5");
$separate = $array;
$series =' ';


foreach ($array as $item){
    $series .=$item;
    echo $series;
    if (next($separate )) {
        echo ','; // Add comma for all elements instead of last
    }
}

?>

输出.. enter image description here