krushio vida krushio vida - 6 months ago 20
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 :



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) . ']';