PHP change array key in foreach

PHP change array key in foreach or php rename array key for mapping array. Here is example for replace array key using foreach.

As like above detail here we learn array mapping step by step.

What will you learn from here? Answer is array mapping, means php change array key using foreach.

Why need php change array key?

Mostly for array mapping to make array with new key, so it can be use in another process.

Steps to php change array key

  1. Create mapped key array
  2. Change or replace key in array using foreach
  3. Extra tip: Reverse array mapping

Ok, let’s start learning array mapping by executing above step one by one.

Create mapped key array

Below are arr(source array) and mapped(old and new key map array) array.

$arr = [
    'old1' => 'val1',
    'old2' => 'val2',
    'old3' => 'val3',
    'dont_change' => 'no_change',
];

$mappedArr = [
    'old1' => 'new1',
    'old2' => 'new2',
    'old3' => 'new3',
];

Change or replace key in array using foreach

Now make foreach on source array and check in mapped array for key to replace. If it found use that new key in newly preparing array in loop, otherwise set old key.

$resultArr = [];
foreach( $arr as $k => $v) {
    $resultArr[$mappedArr[$k] ?? $k] = $v;
}

$resultArr;
//Array ( [new1] => val1 [new2] => val2 [new3] => val3 [dont_change] => no_change )

Extra tip: Reverse array mapping

Now if you want to reverse mapping on resultArr and want to make it like original source array. Just flip mapped array so keys and value change and again make foreach on resultArr to generate original array.

$originalArr = [];
$reverseArr = array_flip($mappedArr);

foreach( $resultArr as $k => $v) {
    $originalArr[$reverseArr[$k] ?? $k] = $v;
}

$originalArr;
//Array ( [old1] => val1 [old2] => val2 [old3] => val3 [dont_change] => no_change )

Now you think where this type of process used. Above process useful when you receive source array in specific format but to use it or store its data, need to change with different format.

Also again you need to return data in old format from stored array or some process result which always comes in different format. Sometime useful in API etc.,

1 Comment

Comments are closed.