Reputation: 52
I want to "map" values obtained from an excel file.
If $row['type']
contained 'TYPE ONE' I would expect to get 'value-one'. But instead, I get an error.
I don't know if that's just not how associative arrays work in PHP.
$arrType = [
'TYPE ONE' => 'value-one',
'TYPE TWO' => 'value-two',
];
$key = $row['type'];
echo $arrType[$key]; //Error Undefined index: TYPE ONE
If I manually assign the string value... it works...
$arrType = [
'TYPE ONE' => 'value-one',
'TYPE TWO' => 'value-two',
];
$key = 'TYPE ONE';
echo $arrType[$key]; //value-one
EDIT 27 Aug 2021 It works on production. For the time, we will leave it like that... We think the problem is excel encoding or something...
EDIT 14 Sep 2021 It was an issue with special characters. It worked on production but still, some regex was used to remove them.
$type = preg_replace('/[^a-zA-Z ]/', '', implode(str_split($arrType[$key])));
echo $arrType[$type]; //Expected value
Upvotes: 1
Views: 947
Reputation: 52
It was an issue with special characters. It worked on production but still, some regex was used to remove them.
$type = preg_replace('/[^a-zA-Z ]/', '', implode(str_split($arrType[$key])));
echo $arrType[$type]; //Expected value
Upvotes: 0
Reputation: 11
Something to consider
$row = [
'TYPE'=>'TYPE TWO',
'type'=>'TYPE ONE ' //possible spaces -- use trim()
];
$arrType = [
'TYPE ONE' => 'value-one',
'TYPE TWO' => 'value-two',
];
$key = $row['type'];
echo $arrType[$key]; //Notice: Undefined index: TYPE ONE
$key = trim($row['type']);
echo $arrType[$key]; //value-one
Upvotes: 1