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);
 }
?>

Recommended Answers

All 2 Replies

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);
}

then go in C++ category. dont get mixed up this is PHP.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.