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?
Use array_combine function:
$combined = array_combine($bar, $foo);
print_r($combined); gives
Array
(
[abc] => foo
[xyz] => bar
)
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With