3y3skill3r
3y3skill3r

Reputation: 1026

PHP array with value returns NULL

I have an array which is converted from CSV file. I have there two keys ID and NAME.

If I show key NAME everything is OK. But when i tried to get key ID, i always get NULL but key ID have value set.

enter image description here

function convertCsvToArray($filename='', $delimiter=';')
{
  if(!file_exists($filename))
    return FALSE;

  $header = NULL;
  $data = array();
  if (($handle = fopen($filename, 'r')) !== FALSE)
  {
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
    {
      if(!$header)
        $header = $row;
      else
        $data[] = array_combine($header, $row);
    }
    fclose($handle);
  }
  return $data;
}

$array = convertCsvToArray('/path/to/csv/categories.csv',';');

/*
$array structure is
  array(2){
    ["ID"] => 3
    ["NAME"] => Some name
  }
*/
foreach($array as $category){
  var_dump($category["ID"]); //return NULL
  var_dump($category["NAME"]); //return "Some name"
}

CSV dump

ID;NAME
3;Značkové nealko nápoje
4;Nízkoenergetické nápoje
5;Minerálne vody, sóda
6;Tetrapack 0.2l a 0.5l

print_r for $array

Array
(
    [0] => Array
        (
            [ID] => 3
            [NAME] => Značkové nealko nápoje
        )

    [1] => Array
        (
            [ID] => 4
            [NAME] => Nízkoenergetické nápoje
        )
)

print_r for $category

Array
(
    [ID] => 3
    [NAME] => Značkové nealko nápoje
)

Upvotes: 5

Views: 2823

Answers (1)

Benoit Esnard
Benoit Esnard

Reputation: 2075

The problem here comes from BOM.

Invisible characters are added at the begining of the file, so they are prefixed to the "ID" key, so PHP can't find the ID key, and shows NULL values.

Convert your CSV file to UTF-8 without BOM and it will fix your problem.

Upvotes: 5

Related Questions