0

I would like to delete multiple lines from a CSV file.

I have an array (called $manual) setup:

Array
(
    [0] => A
    [1] => B
    [2] => C
    ...

My CSV looks like this:

A;3h2jhkj
B;ewrwer
C;fsfsdf
D;adsfsdf
E;sdfet
F;35435345f

My code to delete the lines are (not working):

foreach ($manual as $filename) {
        $table = fopen('logs/error.log','r');
        $temp_table = fopen('logs/error_temp.log','wa+');

        while (($data = fgetcsv($table, 2048, ";")) !== FALSE) {
            if($data[0] == $filename){
                continue;
            }
            fputcsv($temp_table,$data);
        }
        fclose($table);
        fclose($temp_table);
        //$done = "YES";
    }

I realise why it's not working but can't get it to work.

What I want is all lines in the CSV that have a first column matching a value in the array to be deleted so the resulting CSV file from the above would yield:

D;adsfsdf
E;sdfet
F;35435345f
1
  • matching (exect) something in the array, will be in_array Commented Jul 28, 2019 at 16:12

1 Answer 1

2

You don't need to iterate $manual, just check if value in the $manual.

$table = fopen('logs/error.log','r');
$temp_table = fopen('logs/error_temp.log','wa+');

while (($data = fgetcsv($table, 2048, ";")) !== FALSE) {
    if(in_array($data[0], $manual, true)){
        continue;
    }
    fputcsv($temp_table,$data);
}
fclose($table);
fclose($temp_table);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I wouldn't have to negate it would I as I am saying if it was in the array then I don't want it...
I miss that. Fixed.
Thanks - when reading my question out I sorted but thanks for the reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.