Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
How to remove the last character from last string in a While loop?

I am trying to insert a PHP loop with data from my mysql database inside a Google Charts script.

My result from the database looks like this:

$result = $wpdb->get_results(
    "Query"); 

The loop that I am trying to make is supposed to look like this

['$result',  $result],

And this is what I have come up with so far

$count = 0;
while ($count < count($result)) {
    echo "['" . $result[$count]->dato . "', " . $result[$count]->vaegt . "].<br>";
    $count++;
    }

Which create the string that I am looking for. The problem is that I need to remove the comma from the last string in the loop.

I have tried the function LTRIM, but it removes it from every string in the loop, not just the last.

What would be the best solution to fix this problem?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

First off, don't use count() for a fixed result in a loop. It may look convenient, but it's slower as it performs the operation over and over on each iteration. Assign the count result to a variable first. And personally, I would use a for() loop here.

Secondly, you need to use a condition inside the loop. Rather than trying to remove the last comma just run a check on the iteration count, if it's not last then add a comma.

$count = count($result);
for($i = 1; $i <= $count; $i++)
{
    echo "....";
    if($i < $count)
    {
        echo ", ";
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

You can use json_encode, I think it will give you the kind of output you want.

Like this :

$arr = array();

foreach ( $result as $res ) {

    $dato = $res->dato;
    $vaegt = $res->vaegt;

    $arr[$dato] = $vaegt; 

}

$output = json_encode($arr);

Then pass $output to JS and use it like this :

var data = new google.visualization.DataTable("your JSON variable");

var options = {
 title:your option,
 legend:your option,
 chartArea:your option
};

var chart = new google.visualization.LineChart(document.getElementById("the ID of the HTML element in which you want to output the result"));

chart.draw(data, options);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!