fgetcsv: counting row length efficiency

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

fgetcsv: counting row length efficiency

Post by dsdsdsdsd »

hello:
I am opening a .csv file which will then be sent over to a mysql table;
I am searching for the longest row in the .csv, ie mnoc(max_number_of_columns);

Code: Select all

function mnoc($csv_file)
  { $mnoc = 0;
    $file_pointer = fopen( $csv_file , "r");
    while ($row_pointer_array = fgetcsv($file_pointer, 2000, ",")) 
      { if ( count($row_pointer_array) > $mnoc)
	      { $mnoc = count($row_pointer_array);
	      };
       };
  };
this seems like a terribly inefficient way to count the 'length' of each row in a .csv file;

any thoughts?

thanks
Shannon Burnett
Asheville NC USA
TheBentinel.com
Forum Contributor
Posts: 282
Joined: Wed Mar 10, 2004 1:52 pm
Location: Columbus, Ohio

Re: fgetcsv: counting row length efficiency

Post by TheBentinel.com »

dsdsdsdsd wrote:I am searching for the longest row in the .csv, ie mnoc(max_number_of_columns);

this seems like a terribly inefficient way to count the 'length' of each row in a .csv file;
I didn't say anything yet because I figured some guru was going to tell you about the count_columns_in_a_csv_file() function and anything I said would just make me look stupid.

But since no one's said anything yet, I'll say it:

I can't imagine any method for this that wouldn't involve reading every line and counting the columns, comparing it to a maxColumns variable, and ending up with a result. This is what you have done.

There's probably a more efficient function for one piece or another, but your biggest hit is reading the file and you can't get around that, so any increase in the effiency of counting the columns isn't going to buy you much.

The good news is that you've put it in a function, so if you discover a better way to do it, you can just update your function. And for now, I doubt it's a performance hog anyway.

My two cents worth, cheerfully refunded if not fully satisfied.
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

Post by dsdsdsdsd »

hello Dave;
no it is not a performance hog; in fact this function will only be used once a month and only takes about 2 or 3 seconds it seems;

I am thinking about a 'premonition iterative' method; something like:

Code: Select all

function determine_max_col(premonition)
"I think that there is no row longer than" premonition
if(T)  //ofcourse you have to count every row to figure this out
  { determine_max_col(premonition-1);
  }
Post Reply