Jump to content

Removing Last comma from an array row


azonicds2

Recommended Posts

Hi guys

 

Had some great help from here before so thought id try my luck again.

 

Basically i have an array query that works fine, but the echo is going into a piece of Javascript, its basically telling the Java what image paths to use for a Slideshow, each of these needs to be seperated by a comma. Accept for the last one in the array needs to have the comma removed.

 

I can remove the last comma for each row no problem but thats where the problem lies. I only want to remove it from the last row in the array.

 

Any ideas?

 

My code is as follows:

 

<?php
$query2 = mysql_query("SELECT * FROM homeimages ORDER by Filename ASC") or die(mysql_error());
while ($row2=mysql_fetch_array($query2)){

$string = "['http://www.benbrownphotography.co.uk/images/home/upload/".$row2['Filename']."'],";
$output = substr_replace($string,"",-1);

echo "$output";

}
?>

 

This is fine for if there is only one row in the database but when you add more it is obviously removing the comma from every row.

 

How can i remove it only from the last row in the array?

 

Thanks a lot in advance!

Danny

Link to comment
Share on other sites

Another method would be to use implode. I rewrote your code and enhanced it (in a few parts):

 

function get_file_name($resource) {
  list($filename) = mysql_fetch_row($resource);
  return $filename;
}

$result = mysql_query('SELECT Filename FROM homeimages ORDER by Filename ASC');
$files = array();
if (false !== $result && ($num_rows = mysql_num_rows($result)) > 0) {
    $files = array_map('get_file_name', array_fill(0, $num_rows, $result));
}

echo '["http://www.benbrownphotography.co.uk/images/home/upload/',
       implode('"],["http://www.benbrownphotography.co.uk/images/home/upload/', $files),
     '"]';

 

If you have PHP5.3 running on your server you may use closures instead of get_file_name()

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.