1

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

9
  • What error do you get? Commented Jul 24, 2021 at 23:04
  • 1
    Undefined index: TYPE ONE Commented Jul 24, 2021 at 23:09
  • 2
    This obviously means that value of $row['type'] is not what you expect. var_dump($row['type']) Commented Jul 24, 2021 at 23:13
  • 1
    Already tried casting to string Commented Jul 24, 2021 at 23:38
  • 1
    Does your value contains quotes? Can you please try $key = trim($row['type'], '"');? Commented Jul 25, 2021 at 0:20

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion but already tried trimming and casting.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.