Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rewrite keys of array by another array

I want to rewrite array "foo"'s numeric keys with string keys. The relation is saved in another array "bar".

$foo = array(
 1 => 'foo',
 2 => 'bar',
 ...
);

$bar = array(
 1 => 'abc',
 2 => 'xyz',
 ...
);

$result = array(
 'abc' => 'foo',
 'xyz' => 'bar',
 ...
);

What is the fastest way to achieve this result?

like image 761
steros Avatar asked Feb 07 '26 01:02

steros


2 Answers

Use array_combine function:

$combined = array_combine($bar, $foo);

print_r($combined); gives

Array
(
    [abc] => foo
    [xyz] => bar
)
like image 114
Zbigniew Avatar answered Feb 08 '26 13:02

Zbigniew


NullPointer's example will fail if the keys/values in both arrays ($foo and $bar) will be in different order. Consider this:

$foo = array(
    1 => 'foo',
    2 => 'bar',
);

$bar = array(
    2 => 'xyz',
    1 => 'abc',
);

If you run array_combine($foo, $bar) like before, the output will be

array(2) {
  ["foo"]=>
  string(3) "xyz"
  ["bar"]=>
  string(3) "abc"
}

This simple loop, however, should work:

$output = array();
foreach ($bar as $from => $to) {
    $output[$to] = $foo[$from];
}
like image 29
Andris Avatar answered Feb 08 '26 15:02

Andris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!