Search code examples
phparrayshtml-listsdelimiter

How to remove last comma from each array in foreach?


I have a multidimensional array and I am trying to put comma delimiter and remove the last comma from each array so far I try this.

$cars=array("Volvo","BMW","Toyota","Honda","Mercedes");
$chunks =(array_chunk($cars,2));
foreach ($chunks as $key) {
    echo "<ul>";
    $data = array();
    foreach ($key as $value) {
        $data[] ="<li>".$value."</li>".",";
    }
    rtrim($data, ",");
    echo "</ul>";
}
foreach ($data as $key ) {
    echo $key;
}

Expected Output:

<ul>
    <li>Volvo,</li><li>BMW</li>
</ul>
<ul>
    <li>Toyota,</li><li>Honda</li>
</ul>
<ul>
    <li>Mercedes</li>
</ul>

Notice that there is no comma after BMW, Honda, or Mercedes.


Solution

  • Here is a less-loopy method that uses array_splice() instead of array_chunk(). No count() calls, no incrementing counters, just one loop.

    Code: (Demo)

    $cars=array( "Volvo","BMW","Toyota","Honda","Mercedes");
    while($cars){                             // while there are still elements in the array...
        $chunk=array_splice($cars,0,2);       // extract first two elements (reducing $cars)
        if(isset($chunk[1])){$chunk[0].=',';} // add comma to 1st element if 2nd element exists
        $output[]=$chunk;                     // add extracted elements to multi-dim output
    }
    var_export($output);
    

    Output:

    array (
      0 => 
      array (
        0 => 'Volvo,',
        1 => 'BMW',
      ),
      1 => 
      array (
        0 => 'Toyota,',
        1 => 'Honda',
      ),
      2 => 
      array (
        0 => 'Mercedes',
      ),
    )
    

    The implementation for your unordered list is even simpler -- just add the comma to the joining string </li><li> in the implode() call: ,</li><li>. This also improved code versatility with larger "chunks". (Whereas my first code is only suited for subarrays with two elements.)

    Code: (Demo)

    $cars=array( "Volvo","BMW","Toyota","Honda","Mercedes");
    while($cars){
        $chunk=array_splice($cars,0,2);
        echo "<ul><li>",implode(",</li><li>",$chunk),"</li></ul>";  // add comma to implode's glue string
    }
    

    Output:

    <ul>
        <li>Volvo,</li><li>BMW</li>
    </ul>
    <ul>
        <li>Toyota,</li><li>Honda</li>
    </ul>
    <ul>
        <li>Mercedes</li>
    </ul>