tags:

views:

55

answers:

3

I have a script which allows the user to create a simple poll, each poll's ID is stored in a text file seperated by a comma: like so:

001,003,005,

I then use a foreach loop to get these poll ID's from the text file.

All relativly simple, however the way in which I create the row of text in the file always add's a comma (,) at the end of each ID. This throws the following error for PHP:

Warning: Invalid argument supplied for foreach() in

How can i ensure that list of ID's never ends with a comma, or that it gets ignored? Like this:

001,003,005

This is how I currently add the ID: The ID is the time plus 'tpid':

    if ($handle2) {
        fwrite($handle2, "tpid".time().",");
        fclose($handle2);
    }

So here i add the comma fwrite($handle2, "tpid".time().",");

And I get the ID's from the text file like so:

$pollids  = "pollids.txt";
$contents = file_get_contents($pollids);
$pollfields = explode(',', $contents);
+1  A: 
  • Why not pre-pend it?
  • Why not implode before saving to a file?
  • Why not check for null before doing processing?
Daniel A. White
+1  A: 

Do something like this:

if it is a new file write just your "ID"

if it is a existing file, write your id like so: ',tpid' . time ()

that way you won't get commas at the end of the file

Jan Hančič
+6  A: 

Trim the start/end commas out with line 3 (below)

$pollids  = "pollids.txt";
$contents = file_get_contents($pollids);
$contents = trim($contents, ',');
$pollfields = explode(',', $contents);
adam
I believe this is the simplest way.
Blair McMillan