Forum Moderators: coopster

Message Too Old, No Replies

Removing a comma from the end of an array

         

cookie2

11:25 pm on Jun 18, 2004 (gmt 0)

10+ Year Member



I am reading a file into an array using this:

$listFile = "add2db.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
fclose($fp);

The very last character in that $listFile will always be a comma. What I need to do is remove that last comma (and only that comma) from $buffer before I can continue on. What do I need to do to accomplish this?

Glacai

1:28 am on Jun 19, 2004 (gmt 0)

10+ Year Member



$buffer = rtrim($buffer, ",");

cookie2

2:08 am on Jun 19, 2004 (gmt 0)

10+ Year Member



Thanks but that it were that easy. :( It does not work. I tried using
$listFile = "add2db.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
fclose($fp);
$buffer = rtrim($buffer, ",");
echo "$buffer";
die;

and the last comma is still there. Any other ideas?

Glacai

2:50 am on Jun 19, 2004 (gmt 0)

10+ Year Member



Works ok for me, is there always only one comma at the end? Could also try this

if($buffer[($len = strlen($buffer)-1)] == ',') $buffer[$len] = '';

Added:
Or it could be because of a newline or eof so try changing rtrim to
$buffer = rtrim($buffer, "\n,");

[edited by: Glacai at 3:18 am (utc) on June 19, 2004]

johnerazo

3:15 am on Jun 19, 2004 (gmt 0)

10+ Year Member



The very last character in that $listFile will always be a comma. What I need to do is remove that last comma (and only that comma) from $buffer before I can continue on. What do I need to do to accomplish this?

Since there will always be a 'comma' at the end, you can try this ...


$buffer = substr($buffer, 0, strlen($buffer)-1);

It gets the first character of $buffer up to the end minus that 1 character which is the 'comma'.