Skip to content
Advertisement

Echo Array Values in Comma Separated List

I am selecting values from my database, when I dump the $results I get;

array (
  0 => 
  (object) array(
     'FieldName' => 'certification_name',
     'FieldValue' => 'White Belt',
  ),
  1 => 
  (object) array(
     'FieldName' => 'certification_name',
     'FieldValue' => 'Yellow Belt',
  ),
)

I want to display the following on my page;

Certification List: White Belt, Yellow Belt

I have created a loop but when I echo the result I get this;

Certification List: Array Array

My PHP code;

foreach ($results as $result) {

    $name = $result->FieldName;
    $value = $result->FieldValue;

    $items[] = array(
        'name' => $name, 
        'value' => $value
    );
}

$items = implode("n", $items);
echo 'Certification List: ' .$items;

What do I need to change in order to get this working?

Advertisement

Answer

You shouldn’t push arrays into $items, just push the values.

foreach ($results as $result) {
    $items[] = $result->FieldValue;
}
$item_list = implode(", ", $items);
echo "Certification List: $item_list";

You can also replace the loop with:

$items = array_column($results, 'FieldValue');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement