Search code examples
phparraystrimfwrite

PHP Delete txt line and then remove line works BUT if the delete is the last line, it won't remove blank line


Use code below to delete a line from a text file. If the deleted item is NOT the last element, it works fine. Deletes the line entirely.

    $panel_dir = 'host.txt';
    $panel_data = file($panel_dir);
    $panel_out = array();
    foreach($panel_data as $panel_line) {
        if(trim($panel_line) != $panel_del) {
            $panel_out[] = $panel_line;
        }
    }

    $f_panel = fopen($panel_dir, "w+") or die("Error");
    foreach($panel_out as $panel_line) {
        fwrite($f_panel, $panel_line);
    }
    fclose($f_panel);  
}

BUT if the deleted item is the LAST element, it will remove the line and then leave a blank line.

Open to better methods for deleting the entire line from text file.


Solution

  • Use the array_map to trim all the lines. Use the unset to delete the matching item from the array. You don't need to use the $panel_out variable. Then use the implode to turn the array into a string separated by a new line.

    $panel_dir = 'host.txt';
    $panel_data = array_map('trim', file($panel_dir));
    
    foreach($panel_data as $key => $panel_line) {
        if($panel_line == $panel_del) {
            unset($panel_data[$key]);
        }
    }
    
    $f_panel = fopen($panel_dir, "w+") or die("Error");
    fwrite($f_panel, implode("\n", $panel_data));
    fclose($f_panel);