1

I have function which read csv file in the array. my code is

public function csvExtract() 
     {   


       $file_handle = fopen(text.csv, 'r');

       while (!feof($file_handle) )
        {
            arraydata[] = fgetcsv($file_handle, 1024);
        }

        fclose($file_handle);
    }

what i need is:

my file contain last row which has FINAL TOTAL that row i want to skip .

how to do this. Can any one help me on this.

thank you.

3 Answers 3

2

Once you've finished your read loop:

end($arraydata);
$key = key($arraydata);
unset($arraydata[$key]);

or simply

array_pop($arraydata);
Sign up to request clarification or add additional context in comments.

Comments

1

You can skip any loop in PHP with the continue statement. This will only skip 1 iteration of the loop, as apposed to the break statement, which will end the loop completely.
Using this, you can form a condition for when the loop should skip:

while (!feof($file_handle)) {
    $csv = fgetcsv($file_handle, 1024);
    // check your condition and skip if needed...
    if (in_array('FINAL TOTAL', $csv)) continue;
    $data[] = $csv;
}

2 Comments

thank you NDM. but here one small problem when i used this it is giving me warring as follows :Warning: in_array() expects parameter 2 to be array, boolean given in 99 where line 99 have this statement if (in_array('FINAL TOTAL', $csv)) continue;
Well, you have to make sure the code in the if is correct for your data, also be sure to check if fgetcsv returns an array, as it returns false on failure
0

quick dirty solution

 ...
 fclose($file_handle);
 if($arraydata) {
    unset($arraydata[count($arraydata)-1)]);
 }

just "delete" the last row from your import

Comments

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.