krushio vida krushio vida - 1 year ago 68
PHP Question

Create a list like array when echoed in php

I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,

i would want my final result to look like


When i try the code below:

$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);

echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {

$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
echo ']'

The result is :


Answer Source

You are doing it wrong. ltrim($listwithcoma,',') has no effect.

ltrim — Strip whitespace (or other characters) from the beginning of a string

You can try a simple way with implode.

$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
   $list[] =  $row['column'];

echo '[' . implode(',', $list) . ']';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download