Comma separated list from array

Issue

I am wondering how to:

  • Make comma-separated list
  • Strip last comma from list

Here’s an array example:

Array
(
    [name] => Array
        (
            [0] => Some message to display1
        )
    [test] => Array
        (
            [0] => Some message to display2
        )
    [kudos] => Array
        (
            [0] => Some message to display3
        )

)

I want to display it like this:

Comma-List: Some message to display1, Some message to display2, Some message to display3

Solution

so, revising my answer to actually address your question, you could do it with nested foreach loops like this:

<?php

$a1 = array(
    'name' => array( 0 => 'Some message to display1'),
    'test' => array( 0 => 'Some message to display2'),
    'kudos' => array( 0 => 'Some message to display3'),
    );

$final = "";
foreach($a1 as $innerarray){
    foreach($innerarray as $message){
        $final .= $message.", ";
    }
}

echo substr($final,0,-2);
?>

Answered By – Hurricane Hamilton

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published