3

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?

2 Answers 2

7

Use array_combine function:

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

print_r($combined); gives

Array
(
    [abc] => foo
    [xyz] => bar
)
Sign up to request clarification or add additional context in comments.

Comments

1

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];
}

2 Comments

Why not just ksort both arrays? :P
Note that OP explicitly defined array indexes (1 =>), so I guess we can assume that it has already been taken care of, besides we can always reindex both arrays (e.g. array_values). array_combine seems to be short and simpler solution, at least for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.