PHP: Undefinierter Index, auch wenn er existiert
Es macht mich verrückt ... Ich versuche eine CSV-Datei zu analysieren und es gibt ein sehr merkwürdiges Verhalten.
Hier ist die CSV
action;id;nom;sites;heures;jours
i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1
Nun der PHP-Code
$required_fields = array('id','nom','sites','heures','jours');
if (($handle = fopen($filename, "r")) !== FALSE)
{
$cols = 0;
while (($row = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$row = array_map('trim',$row);
// Identify headers
if(!isset($headers))
{
$cols = count($row);
for($i=0;$i<$cols;$i++) $headers[strtolower($row[$i])] = $i;
foreach($required_fields as $val) if(!isset($headers[$val])) break 2;
$headers = array_flip($headers);
print_r($headers);
}
elseif(count($row) >= 4)
{
$temp = array();
for($i=0;$i<$cols;$i++)
{
if(isset($headers[$i]))
{
$temp[$headers[$i]] = $row[$i];
}
}
print_r($temp);
print_r($temp['action']);
var_dump(array_key_exists('action',$temp));
die();
}
}
}
Und die Ausgabe
Array
(
[0] => action
[1] => id
[2] => nom
[3] => sites
[4] => heures
[5] => jours
)
Array
(
[action] => i
[id] =>
[nom] => un nom a la con
[sites] => 1200|128
[heures] =>
[jours] => 1|1|1|1|1|1|1
)
<b>Notice</b>: Undefined index: action in <b>index.php</b> on line <b>110</b>
bool(false)
Der Schlüssel "action" existiert in $ temp aber$temp['action'] returns Undefined
undarray_key_exists returns false
. Ich habe es mit einem anderen Schlüsselnamen versucht, aber immer noch der gleiche. Und absolut kein Problem mit den anderen Schlüsseln.
Was ist daran falsch?
PS:line 110 is the print_r($temp['action']);
EDIT 1
Wenn ich am Anfang jeder Zeile ein weiteres leeres Feld in die CSV-Datei einfüge, wird die Aktion korrekt angezeigt
;action;id;nom;sites;heures;jours
;i;;"un nom a la con";1200|128;;1|1|1|1|1|1|1