PHP Converting an Array to a Formatted String in PHP

Learn how to convert an array into a nicely formatted string in PHP using the join() function or a loop. Find out the advantages and limitations of using join() and how to add custom formatting or exclude specific values.

$array = ["item1", "item2", "item3", "item4"];

$string = join(',', $array);

$string = '';

foreach ($array as $key => $value) {
    $string .= ",$value";
}

$string = substr($string, 1);

$left  = '<b>';
$right = '</b>';

$html = $left . join("$right,$left", $html) . $right;

$string = '';

foreach ($fields as $key => $value) {
    if ('password' != $key) {
        $string .= ",<b>$value</b>";
    }
}

$string = substr($string, 1);

$string = '';
foreach ($fields as $key => $value) {
    if ('password' != $value) {
        if (!empty($string)) { $string .= ','; }
        $string .= "<b>$value</b>";
    }
}