php - How to remove last comma from each array in foreach? -
i have multidimensional array , trying put comma delimiter , remove last comma each array far try this.
$cars=array("volvo","bmw","toyota","honda","mercedes"); $chunks =(array_chunk($cars,2)); foreach ($chunks $key) { echo "<ul>"; $data = array(); foreach ($key $value) { $data[] ="<li>".$value."</li>".","; } rtrim($data, ","); echo "</ul>"; } foreach ($data $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 there no comma after bmw
, honda
, or mercedes
.
here less-loopy method uses array_splice()
instead of array_chunk()
. no count()
calls, no incrementing counters, 1 loop.
code: (demo)
$cars=array( "volvo","bmw","toyota","honda","mercedes"); while($cars){ // while there still elements in array... $chunk=array_splice($cars,0,2); // extract first 2 elements (reducing $cars) if(isset($chunk[1])){$chunk[0].=',';} // add comma 1st element if 2nd element exists $output[]=$chunk; // add extracted elements 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 unordered list simpler -- add comma joining string </li><li>
in implode()
call: ,</li><li>
. improved code versatility larger "chunks". (whereas first code suited subarrays 2 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 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>
Comments
Post a Comment