Reputation: 3563
I have a problem that I can not explain myself. I think it might be an error of PHP or Laravel - or I am doing something I should not.
I have a .csv file with country codes and country names
I want to read the file and seed my database with the data. Therefore I have the following code to get the CSV into an array:
$csv = public_path() . "/assets/countries.csv";
if(File::exists($csv)) {
$content = File::get($csv);
$lines = array();
$lines = explode("\n", $content);
for($i=0; $i<sizeof($lines);$i++) {
$line = $lines[$i];
$line = explode(",",$line);
$lines[$i] = $line;
}
}
So far so good, my $lines array has now all the values with each being an array with 2 indexes, 0 for the code and 1 for the country name.
Doing foreach($lines as $line) and var dumping $line, I get:
array(2) { [0]=> string(2) "AF" [1]=> string(12) "Afghanistan " }
.....
For each entry. But now the following happens:
echo $line[0]; // output: AF
echo $line[1]; // undefined offset 1 error
I tried to check if 1 is a string index or what so ever, see the following code+output:
foreach($lines as $line) {
var_dump($line);
echo 'array_key_exists(1, $line): ';
var_dump(array_key_exists(1, $line));
foreach($line as $key => $col) {
echo 'var_dump($key): ';
var_dump($key);
echo '$col: ' . $col;
echo '$line[$key]: ' . $line[$key];
}
}
(I deleted some echoed breaks for readability) The code produces the following output (for the first result and similar for all others:)
array(2) { [0]=> string(2) "AF" [1]=> string(12) "Afghanistan " }
array_key_exists(1, $line): bool(true)
var_dump($key): int(0)
$col: AF
$line[$key]: AFvar_dump($key): int(1)
$col: Afghanistan
$line[$key]: Afghanistan
How can array_key_exists(1, $line)
result in true, but $line[1]
in an undefined offset: 1 error? Thanks for your help.
EDIT: $line[$key]
is working, while $line[1]
is not. var_dump(1 == $key) results in bool(true) in that case...
EDIT2: If I have the same code without using laravel (file_get_contents then) - I do not get an error. See this fiddle for the code
Upvotes: 0
Views: 1400
Reputation: 3563
I was stupid. Thanks to the guys from laravel.io I realized that the error is neither within PHP nor Laravel but within my data.
There was an empty last row in .csv file. That file couldn't be exploded, resulting in only one single value in $lines[249]
(last entry).
My excuses for this.
Upvotes: 1