Having trouble accessing value of array by key


Question: Having trouble accessing value of array by key

I'm trying to access array values by key ( echo $data['code']), or casting as object, and I'm being hit with Uncaught Exception: Notice: Undefined index: code. For debugging purposes, I've tried to access them by doing this:

 foreach (array_keys($data) as $arrayKey) {             var_dump($data[$arrayKey]);         } 

If I var_dump the $data array, the keys and values are visible in the console output (see below). Please help, I'm going nuts trying to figure this one out. The array is read from a .csv file, encoding is reported as UTF-8 by IDE.


array(26) {   ["code"]=>   string(13) "xxxxxxxxx"   ["category"]=>   string(8) "ANVELOPE"   ["category_url"]=>   string(40) "https://edited"   ["brand"]=>   string(7) "edited"   ["name"]=>   string(3) "AS1"   ["price_reseller"]=>   string(6) "190.87"   ["currency"]=>   string(3) "RON"   ["stock"]=>   string(1) "1"   ["date"]=>   string(10) "14-03-2022"   ["url"]=>   string(68) "https://edited"   ["latime"]=>   string(3) "165"   ["diametru"]=>   string(2) "15"   ["talon"]=>   string(2) "65"   ["sezon"]=>   string(4) "VARA"   ["id_gr"]=>   string(2) "81"   ["id_vit"]=>   string(1) "T"   ["peco"]=>   string(1) "E"   ["ploaie"]=>   string(1) "C"   ["zgomot"]=>   string(2) "71"   ["image"]=>   string(70) "https://edited"   ["grupa"]=>   string(6) "Turism"   ["tehnologie_suplimentara"]=>   string(2) "--"   ["m_s"]=>   string(2) "NU"   ["Nr_unde"]=>   string(1) "3"   ["id_produs"]=>   string(5) "edited"   ["info_dot"]=>   string(8) "DOT 2017" } 

Total Answers: 2


Answers 1: of Having trouble accessing value of array by key

In order to access the key value of an array you have to use $key variable on your foreach as follow

foreach (array_keys($data) as $key => $arrayKey) { 

to dump the keys of your object do the following code.

         foreach (array_keys($data) as $key => $item) {             dump($key);                  // this will return the key value             dump($item);                // this will return the value of the key             dump($key . '--' . $item); // will return the key and value of your object         }  

Answers 2: of Having trouble accessing value of array by key

If anyone ends up on this questiong, turns out the file I was reading contains php error ASCII characters, which were not printed in the console output.

I solved this by sanitizing with /[\x00-\x1F\x7F-\xFF]/ to remove those characters. The code snippet is available below.

The reporting as UTF8 was done by my PhpStorm.

$regex = <<<'END' /[\x00-\x1F\x7F-\xFF]/ END; preg_replace($regex, '$1', $stringToSanitize)