phparraysassociative-arrayundefined-index

Undefined index in array but it is there


I have an array called $csv. The header columns are contained within $csv[0]. I have a loop that goes in and overwrites some data in the $csv array starting at index 1.

For some reason it is no longer getting any value when I try to output $csv[1]['CRM ID'] even though the value is there when I do a var_export of $csv[1].

I am able to read data out of $csv[1]['Agency'] just fine. Is it something to do with the space? It has been working up until now until a seemingly unrelated piece of 3rd-party code was changed.

// Agency ID - prefix + zerofill
$agency_id_n = strpos($csv[$i]['Agency'], 'A') === 0 ? (int) ltrim($csv[$i]['Agency'], 'A') : (int) $csv[$i]['Agency'];
$csv[$i]['Agency'] = $agency_id_p = 'A' . str_pad($agency_id_n, 5, '0', STR_PAD_LEFT);

// CRM ID - prefix + zerofill
echo "<h1>\$csv :-</h1><pre>" . print_r($csv, true) . "</pre>";
echo "<h1>\$csv[1] :-</h1><pre>" . var_export($csv[1], true) . "</pre>";
echo "<h1>yyyyy = {$csv[1]['CRM ID']} / " . var_export($csv[1]['CRM ID'], true) . "</h1>";

$crm_id_n = strpos($csv[$i]['CRM ID'], 'C') === 0 ? (int) ltrim($csv[$i]['CRM ID'], 'C') : (int) $csv[$i]['CRM ID'];

echo "<h1>has c = " . (strpos($csv[$i]['CRM ID'], 'C') === 0 ? 'yes' : 'no') . "</h1>";
echo "<h1>val = {$csv[$i]['CRM ID']}</h1>";
echo "<h1>y = $crm_id_n</h1>";
die("<h1>csv...</h1><pre>" . print_r($csv, true) . "</pre>");


Solution

  • The culprit was fgetcsv being susceptible to byte-order marks (BOMs) - from a comment on the PHP manual:

    This function has no special BOM handling. The first cell of the first row will inherit the BOM bytes, i.e. will be 3 bytes longer than expected. As the BOM is invisible you may not notice.

    Excel on Windows, or text editors like Notepad, may add the BOM.