How to avoid adding a comma to the last line?

I use the following code to add a comma ,at the end of each file name. After that with the help explodeI put the strings in an array.

An array of images, if I repeat it, it shows a.jpg, b.jpg, c.jpg (please note the last comma at the end of c.jpg)

How can I avoid adding a comma to the last line found?

<?php       
 while($image = mysql_fetch_array($images)) { 
 $images_path .= $image['FILE_NAME'].',';
}

$images_array = explode(",", $images_path);
?>
+3
source share
5 answers

Use rtrim()by providing a comma as the second parameter ascharacter mask

$images_path = rtrim($images_path,","); //<---- The added code
$images_array = explode(",", $images_path);
+4
source

Why add it to a string and then convert it to an array if you can add it right away?

$images_array = array();
while($image = mysql_fetch_array($images)) { 
    $images_array[] = $image['FILE_NAME'];
}
+3
source

:

  • , .
  • , ( , )

:

  • , ,

, (.. ).

:

<?php       
 while($image = mysql_fetch_array($images))
  {
    $images_array[] = $image['FILE_NAME'];
  }
?>

, , variable , (, , ), , .

!

+1

, ,

explode(',', $images_path, -1);

, , .

0

, , .

, , Apache/Google, , , implode/explode; split/join; , .

, , , .

, , , -, , , , , , , / .

:

(pseudocode)
<?php       
$images_path = "";

// Base case
if($image = mysql_fetch_array($images)) {
  $images_path .= $image['FILE_NAME'];
}

// If multiple results, iterate
while($image = mysql_fetch_array($images)) { 
  $images_path .= ',' . $image['FILE_NAME'];
}

$images_array = explode(",", $images_path);
?>

Switch it from append to comma when there are several. Now you will never have to remove the extra comma or execute any destructive command. It looks very much like making proof, you build the base case, and then build the base.

0
source

All Articles