Travis Michael Heller
Travis Michael Heller

Reputation: 1248

Get rid of last comma using PHP or Javascript

I have tried many different things to do this and all my ideas have failed me. How do i get rid of the last comma after running this while loop?

<body onload="
    <?php while($row = mysql_fetch_assoc($thing3)): ?>
        checkEdits_<?php echo $row['directory_name']; ?>(),
    <?php endwhile; ?>
">

It adds the last comma at the end which ruins the whole script.

The php while(loop) puts this out when ran through the dom:

<body onLoad="checkEdits_juk(), checkEdits_HTML(), checkEdits_JAVASCRIPT(), checkEdits_JQUERY(),">

except i don't want the last comma at the end. Is their a way to get rid of it?

Upvotes: 0

Views: 271

Answers (5)

tptcat
tptcat

Reputation: 3961

Use rtrim to take off the last comma. I'd rewrite like this:

<?php 
$onload = "";
while($row = mysql_fetch_assoc($thing3)) {
    $onload .= "checkEdits_" . $row['directory_name'] . ", ";
}
$onload = rtrim($onload, ', ');
?>

<body onload="<?php echo $onload; ?>">

Upvotes: 0

dm03514
dm03514

Reputation: 55962

you can put your data in an array and uese the implode function

  $directory_names = array();
  while($row = mysql_fetch_assoc($thing3)) {
    $directory_names[] = $row['directory_name'];
  }
  echo implode(', ', $directory_names);

Upvotes: 7

Uladzimir Pasvistselik
Uladzimir Pasvistselik

Reputation: 3921

Or you can use:

<body onload="function() {
    <?php while($row = mysql_fetch_assoc($thing3)) { ?>
        checkEdits_<?php echo $row['directory_name']; ?>(); 
    <?php } ?>
}">

Upvotes: 1

Draculater
Draculater

Reputation: 2278

With your array of MYSQL rows, use php's join function (implode) http://php.net/manual/en/function.join.php

Upvotes: 1

Ayush
Ayush

Reputation: 42450

substr($yourString, 0, strlen($yourString) - 1);

This returns a substring of your string that contains everything from the 0th index to the last - 1 position.

Upvotes: 3

Related Questions