0

I have a function that is supposed to save an array to a file that I give to it, but every array variable is supposed to be tab separated...At this point I have the function but it's not creating any file and it's not writing anything to it...Also for some reason when I try to give an array from another page, it giving me an undefined index error, even though I started a session on both page..can you help with either of the too

function saveorder($file,$arr){
@ $fp = fopen($file, 'w');

    flock($fp, LOCK_EX);

    if (!$fp) {
      echo "<p>Your order could not be processed at this time.</p>";
    }
    else {
      fwrite($fp, _SESSION);
      flock($fp, LOCK_UN);
      fclose($fp);

      echo("<p>Order written to $file file.</p>");
    }    

}
Will Barangi
  • 145
  • 1
  • 2
  • 13
  • You are actively suppressing errors with the '@' symbol. Never do that and ask "why doesn't this work?". It's like gagging PHP and then come asking us what's wrong, while PHP is probably trying to tell you anyway. – Gerard van Helden Oct 02 '16 at 14:40

1 Answers1

0

No idea what is _SESSION ($_SESSION maybe?), no idea how you want to write your array but this code works for me:

$b = array('test' => 'result', 'another' => 'other');
saveorder('test.txt', $b);
function saveorder($file,$arr){
    @ $fp = fopen($file, 'w');

    flock($fp, LOCK_EX);
    $string = '';
    foreach($arr as $key => $result)
        $string .= "$key: $result \n";

    if (!$fp) {
      echo "<p>Your order could not be processed at this time.</p>";
    }else{
      fwrite($fp, $string);
      flock($fp, LOCK_UN);
      fclose($fp);

      echo("<p>Order written to $file file.</p>");
    }    
}

fwrite second parameter have to be a string, so you format your array as a string however you please

EDIT:

If the array is multidimensional you can use this function as found on this link

$string = implode("&",array_map(function($a) {return implode("~",$a);},$arr));
Community
  • 1
  • 1
Aschab
  • 1,378
  • 2
  • 14
  • 31
  • What if the array is 2 dimensional associated array – Will Barangi Oct 02 '16 at 14:11
  • The important thing is that you turn it into a string, I found this: http://stackoverflow.com/questions/12309047/multidimensional-array-to-string that is by far better than the approach I was going to take, gonna edit to use this. – Aschab Oct 02 '16 at 14:34