0

I am trying to replace an array key (= single letter) with a word. I have a associative array and a $mapKeyArray with the replacement words

$inputArray = ['P' => 72,'T' => 0,'U' => 1,'E' => 0];

function cb_replaceWords($a) {
    $mapKeyArray = array('P' => 'Pink', 'T' => 'Top', 'U' => 'Union', 'E' => 'EX');
    foreach($a as $key) {
//        $a[$key] = $mapKeyArray[$key];
        $a[$key];
    }
    return $a;
}

$outputArray = array_map("cb_replaceWords", $inputArray);
  • Duplicate of https://stackoverflow.com/questions/3053517/how-can-i-remove-a-key-and-its-value-from-an-associative-array – victor Jan 12 '18 at 20:15
  • Possible duplicate of [How can I remove a key and its value from an associative array?](https://stackoverflow.com/questions/3053517/how-can-i-remove-a-key-and-its-value-from-an-associative-array) – Heri Jan 12 '18 at 20:24
  • Sorry I have stated "replace" not "remove" .... – user9191816 Jan 12 '18 at 20:29

1 Answers1

1

Modify your function as:

function cb_replaceWords($a) {
    $result = [];
    $mapKeyArray = array('P' => 'Pink', 'T' => 'Top', 'U' => 'Union', 'E' => 'EX');
    foreach($a as $key => $value) {
        $result[$mapKeyArray[$key]] = $value;
    }
    return $result;    
}

// and there's no need to use array_map
$outputArray = cb_replaceWords($inputArray);

In case your arrays have the same order of keys you can replace all this with array_combine:

$outputArray = array_combine($mapKeyArray, $inputArray);
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • I realise I need your first solution. Could you explain why the foreach picks the right first letter so it seems. I don't see a == and $value is $value from the inputArr not the mapKeyArray?? – user9191816 Jan 13 '18 at 11:59
  • 1
    If `$key` is `P`, then `$mapKeyArray[$key]` is `$mapKeyArray['P']`, which is `Pink` and `$result[$mapKeyArray[$key]]` which is `$result['Pink']` is set to the value `$value`. – u_mulder Jan 13 '18 at 15:33