operations with files and arrays

Discussion in 'PHP' started by t7584, Mar 9, 2006.

  1. #1
    operations with files and arrays

    1. this function adds 1 line to the bottom of the file
    is it possible to add lines to the top?



    $gbfile='gb.txt';

    function add($str){
    global $gbfile;
    $tmp = trim($str);
    $fp=fopen($gbfile,'a+');
    flock($fp, LOCK_EX);
    fwrite($fp, $tmp. "\n");
    flock($fp, LOCK_UN);
    fclose($fp);
    }

    2. there is an array consisting of text lines $lines = file ('entries.txt');
    how to reverse an array (make first line last, last first and so on)

    3.
    this function adds 1 line to the bottom of the file
    how to rewrite a file (remove contents of a file and write information into a file)?


    $gbfile='gb.txt';

    function add($str){
    global $gbfile;
    $tmp = trim($str);
    $fp=fopen($gbfile,'a+');
    flock($fp, LOCK_EX);
    fwrite($fp, $tmp. "\n");
    flock($fp, LOCK_UN);
    fclose($fp);
    }
     
    t7584, Mar 9, 2006 IP
  2. sketch

    sketch Well-Known Member

    Messages:
    898
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    148
    #2
    To add lines to the top of a file, use "r+" instead of "a+" in your fopen().

    To reverse the order of an array, use $newarray = array_reverse($oldarray, TRUE) . Make sure you have TRUE otherwise your keys won't be preserved.

    For the last one, are you talking about simply overwriting a file's contents? If so, use "w+" instead of "a+" in fopen().
     
    sketch, Mar 10, 2006 IP
  3. T0PS3O

    T0PS3O Feel Good PLC

    Messages:
    13,219
    Likes Received:
    777
    Best Answers:
    0
    Trophy Points:
    0
    #3
    T0PS3O, Mar 10, 2006 IP
  4. sketch

    sketch Well-Known Member

    Messages:
    898
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    148
    #4
    Argh, I forgot to mention that ... I had such a witty remark too, "Brought to you in part by PHP.net" LOL
     
    sketch, Mar 10, 2006 IP