1

I would like to replace all numerical keys in $aValues with a textual equivalent stored in $aKeyNames.

$aKeyNames = array(0 => 'foo', 1 => 'bar');
$aValues = array(0 => 'foo content', 1 => 'bar content');

The desired output;

$aValues = array('foo' => 'foo content', 'bar' => 'bar content');

To achieve this I've written the following working code;

foreach ($aValues as $iPos => $aValue) {
    $aValues[ $aKeyNames[$iPos] ] = $aValue; 
    unset($aValues[$iPos]);
}

My concern is that $aValues is very large. Is there a more efficient way to achieve this?

11
  • 2
    Your solutions seems good, since you want to replace the key by the value of the same key in the other array. You can use array_combine(), but you have to make sure both arrays are sorted the same, so the keys are in the same order. Commented Jun 28, 2016 at 14:20
  • array_combine is the best way to do it, if you have same keys in both array. have a look at php.net/manual/en/function.array-combine.php Commented Jun 28, 2016 at 14:20
  • thank you for the comments, Ive just realised a mistake in what I've posted, am just working on an updated question Commented Jun 28, 2016 at 14:23
  • Please accept my apologies, I've updated my question so it now uses a multidimensional array Commented Jun 28, 2016 at 14:30
  • 1
    ok will revert to original and accept answer Commented Jun 28, 2016 at 14:39

1 Answer 1

2

Refer to manual for array_combine:

print_r(array_combine($aKeyNames, $aValues));
Sign up to request clarification or add additional context in comments.

3 Comments

Here comes silent donwvoter.
I would love to know why this was down voted, since it seem to do exactly what the OP asks for? Not helpful to just down vote without any comment.
I'm curious as to why this is downvoted. The only difference I can see is that the OP's code is limited to 2 arrays and the used values are unset in the loop. Lower memory footprint?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.