Ricardo Ricardo - 2 months ago 8
PHP Question

foreach doesn't stop the loop on break

I'm trying to post 3 arrays using

foreach
and for some reason the
break
at the end isn't working and it outputs the whole list (40+) on to the page.

$file = fopen('names.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements

shuffle($line);

$i = 0;

foreach ($line as $number) {
{
if($i==3){ break; } else {
$rtime = mt_rand(1, 7);
echo $number; }

$i++;
}

}


}
fclose($file);


This is kind of how it looks: take.ms/cLgIh, instead it should only show 3 of these usernames.

Answer

I have downloade first sample CSV from here:-http://www.sample-videos.com/download-sample-csv.php

And this code works for me:-

<?php

$file = fopen('SampleCSVFile_2kb.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
      //$line is an array of the csv elements

    shuffle($line);
    $i = 0;
    foreach ($line as $number) {  
        if($i==3){ 
            exit;
        } else {
            $rtime = mt_rand(1, 7);
            echo $number.'<br/>';
            echo $i.'<br/>'; // you can remove this line    
        }

       $i++;
    }


}
fclose($file);
?>

Output on each page refresh:-

http://prntscr.com/cln2ju

http://prntscr.com/cln2nf

Note:- if still not work then check your CSV file. May be it is corrupted.

Conclusion:- And after all discussion it comes to an end that your CSV file is corrupted. But yes code improvement is needed too

Comments