0

Hi, i am trying to create a function that will allow me to update names in a textfile i got. I am actually having problems creating the function. I wAS FOLLOWING AN EXAMPLE I FOUND IN A C++ BOOK, DOING IMPLEMENTATION, BUT GOT MIXED UP. CAN SOMEONE PLEASE HELP ME. THANK YOU.

HERE IS THE CODE:

<?php
$filename = "names.txt";
$data = array();
$key =1;

# get the data from current file
    if (file_exists($filename))
        $data = parse_ini_file($filename, true);
 function txtupdate($k)
{
$fp = fopen($filename, 'w');

    ksort($data);
    foreach ($data as $key=>$dataArray) {
             fwrite($fp, "[$key]\n");
             foreach ($dataArray as $k => $v) {
                      fwrite($fp, "$k=$v\n");
             }
             fwrite($fp, "\n");
    }
    fclose($fp);
 }
?>
3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by vaultdweller123
0

You have to use global keyword for variable if it has been defined out of function.
So, the following code should work:

$filename = "names.txt";
$data = array();
$key = 1;

# get the data from current file
if (file_exists($filename)) {
  $data = parse_ini_file($filename, true);
}
function txtupdate($k) {
  global $data;

  $fp = fopen($filename, 'w');
  ksort($data);
  foreach ($data as $key => $dataArray) {
		fwrite($fp, "[$key]\n");
    foreach ($dataArray as $k => $v) {
      fwrite($fp, "$k=$v\n");
    }
		fwrite($fp, "\n");
  }
  fclose($fp);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.