Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cope with tokenizing from csv file when some fields are empty 1

Status
Not open for further replies.

excession

Programmer
Sep 22, 2004
111
GB
I'm am reading data froma CSV file, after the line is read I am using strtok to break the line up using the comma as the deliminator.

So far so good, the problem arises because some of the fileds are empty and strtok just skipps them. Is the a way round this?

eg:
Line: a,b,,d

I need to get 4 variables:
$val1 = 'a'
$val2 = 'b'
$val3 = ''
$val4 = 'd'

any suggestions?

Thanks in advance
 
Have you considered using explode() instead?
The PHP manual states clearly:
PHPmanual said:
The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:

Example 2. Old strtok() behavior
<?php
$first_token = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(0) ""
string(9) "something"

Example 3. New strtok() behavior
<?php
$first_token = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

Output:

string(9) "something"
bool(false)
 
Thanks, explode() works a treat and sounds great too.
 
I could have done. I'm relatively new to PHP and wasn't aware of the function. Will look it up. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top