Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fgetcsv() - find number of columns

Tags:

php

fgetcsv

I'm trying to determine how many columns a csv file has.

Here's my script, which is only utilizing the first column, but I'm running slightly blind. I want to place a variable that limits the column count. (since I may make a mistake and add a column, or even miss a column)

<?php
$allowedColNum=5;
$batchcount=0;
$file = fopen($file_name, "r"); 
while ($line = fgetcsv($file)){
 /* I want to stop the loop if the $allowedColNum is not correct */                 
  $col = $line[0]; 
  echo $batchcount++.". ".$col."\n";
}

fclose($file);
?>

I'm sure it's one of those easy easy things that I'm not getting.

like image 430
coffeemonitor Avatar asked Oct 06 '11 17:10

coffeemonitor


Video Answer


1 Answers

If I understand, you simply need count($line), because fgetcsv() has returned an array representing one row from the CSV file. The array's count() is therefore the number of source columns.

while ($line = fgetcsv($file)){

  // count($line) is the number of columns
  $numcols = count($line);

  // Bail out of the loop if columns are incorrect
  if ($numcols != $allowedColNum) {
     break;
  }
  $col = $line[0]; 
  echo $batchcount++.". ".$col."\n";
}
like image 53
Michael Berkowski Avatar answered Sep 21 '22 20:09

Michael Berkowski