Home > OS >  Copying elements from one Array to another Array while changing the key
Copying elements from one Array to another Array while changing the key

Time:02-17

I have a huge array of elements that I want to put in a new Array while also changing the key of the elements.

Example ArrayExamplearray

Examplearray (
    "stupidName1" => "dogs",
    "bar" => "foo",
    "names" => "bar",
    "stupidName2" => "cats",
    "cups" => "bar",
    "stupidName3" => "rabbits",
);

I would like the element values of stupidName1, stupidName2, stupidName3 and placing them into a new array i.e Examplearray2. Although I would also like the names changing to a more professional name such as betterName1, betterName2, betterName3.

Example Array - Examplearray2

Examplearray2 (
    "betterName1" => "dogs",
    "betterName2" => "cats",
    "betterName3" => "rabbits",
);

CodePudding user response:

If the existing keys are always in the same order, then just create an array of all keys and combine with the values:

$keys   = ['betterName1', 'bar', 'names', 'betterName2', 'cups', 'betterName3'];
$result = array_combine($keys, $array);

CodePudding user response:

$test = [
    'stupidName1' => 'dogs',
    'bar'         => 'foo',
    'names'       => 'bar',
    'stupidName2' => 'cats',
    'cups'        => 'bar',
    'stupidName3' => 'rabbits',
];

$keys = [ 'stupidName1', 'stupidName2', 'stupidName3' ];

$extracted = array_intersect_key($test, array_flip($keys));

$result = [];
array_walk($extracted, function ($value, $key) use (&$result) {
  $result[str_replace('stupidName', 'betterName', $key)] = $value;
});

print_r($result);

Output:

Array
(
    [betterName1] => dogs
    [betterName2] => cats
    [betterName3] => rabbits
)
  • Related