Search code examples
phparraysindexingencodingfile-encodings

Can't access array element even if it is shown in print_r() / var_dump()


I get the error:

Notice: Undefined index: marca

When I'm trying to do this:

echo $data[0]['marca'];

But if I print the array, like this:

print_r($data[0]);

The output is:

Array ( [marca] => Jack&co [stock] => 10 [nome] => JW0114M2 [codice] => JW0114M2 [caratteristiche] => JW0114M2 Classe articolo: orologio da polso Sesso: unisex Movimento: quarzo Bracciale: acciaio Tipologia: cronografo [prezzo al pubblico €] => 99,00 [sconto %] => 75 [prezzo orologistock €] => 25,00 [img] => http://orologistock.it/virtual_img/ )
       //^^^^^ See the element exists!

So why can't I access the array element?

EDIT:

The output from the source code with var_dump($data[0]); is:

array(9) { ["marca"]=> string(7) "Jack&co" ["stock"]=> string(2) "10" ["nome"]=> string(8) "JW0114M2" ["codice"]=> string(8) "JW0114M2" ["caratteristiche"]=> string(117) "JW0114M2 Classe articolo: orologio da polso Sesso: unisex Movimento: quarzo Bracciale: acciaio Tipologia: cronografo " ["prezzo al pubblico €"]=> string(5) "99,00" ["sconto %"]=> string(2) "75" ["prezzo orologistock €"]=> string(5) "25,00" ["img"]=> string(35) "http://orologistock.it/virtual_img/" } 

I'm getting my array from a .csv file:

function csv_to_array($filename='', $delimiter=';')
{
    if(!file_exists($filename) || !is_readable($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{
                if(count($row) == 9)
                    $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}


$data= csv_to_array($_FILES['data']['tmp_name']);

Solution

  • Encoding of file was wrong, change encoding to UTF-8 solved the Problem.