Reputation: 13
I have an array with two string values, but cannot use one of them. If I use
var_dump($array[0]);
it's result is
array(2) { ["id"]=> string(2) "01" ["name"]=> string(10) "Aquamarine" }
but
var_dump($array[0]["id"]);
shows me NULL.
I've tried changing "id" to sth else, tried using ' instead of ", with the same effect, strlen($array[0]["id"]) also returns 0. The second one ("name") works just fine.
Update: The array is initalized with this code:
$handle = @fopen("stones.csv", "r");
if ($handle) {
while (($row = fgetcsv($handle, 4096, ';')) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
var_dump($array[0]);
var_dump($array[0]["id"]);
var_dump(array_keys($array[0]));
So there are no modifications between dumps, last three rows return this
array(2) { ["id"]=> string(2) "01" ["name"]=> string(10) "Aquamarine" } NULL array(2) { [0]=> string(5) "id" [1]=> string(4) "name" }
Now I see that there are some invisible characters in the "id" key, so the next question is how to get rid of them?
Upvotes: 0
Views: 63
Reputation: 350
trim the key using builtin "trim" function. ref: http://php.net/manual/en/function.trim.php
$handle = @fopen("stones.csv", "r");
if ($handle) {
while (($row = fgetcsv($handle, 4096, ';')) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][trim($fields[$k])] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
var_dump($array[0]);
var_dump($array[0]["id"]);
var_dump(array_keys($array[0]));
Upvotes: 0