Hi everyone,

I am trying to read in a CSV file, so far so good, but now I run into a problem trying to pull out certain entries in the file.

The file looks something like this:

1000,"company name",1,persons name,10/4/2007,W,A,A,"1, 1, PEO"
1000,"company name",1,persons name,9/24/2007,W,A,A,"1, 1, PEO"
9167,company name,1,persons name,10/15/2007,B,A,A,"2, 1, PAY"
9167,company name,1,persons name,9/4/2007,B,A,A,"2, 1, PAY"

I need to extract and display ONLY the lines that have the PEO at the end. The current code looks like this, any help would be greatly appreciated, thanks in advance!

<?php
$row = 1;
$handle = fopen("test.csv", "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
}
fclose($handle);
?>
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
       if(substr($data[count($data) - 1], -3) != 'PEO') {
          continue;
       }
       // rest of loop...
    }
    

      Is this what you're looking for?

      <?php
      $row = 1;
      $handle = fopen("test.csv", "r");
      
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
      {
        $num = count($data);
      
        $lastColumn = trim($data[$num - 1]);
      
        //if last column ends in 'PEO'
        if(substr($lastColumn, strlen($lastColumn) - 3, strlen($lastColumn)) == 'PEO')
        {
          echo "<p> $num fields in line $row: <br /></p>\n";
          $row++;
      
      for ($c=0; $c < $num; $c++) 
      {
        echo $data[$c] . "<br />\n";
      }
        }
      }
      fclose($handle);
      ?>
      
        Write a Reply...