1

i have array1 with following content

array(
'banana',
'apple',
'orange');

and i have a different associative array2 with content and prices of items

array('banana'  => '1.45',
'apple'   => '2.99',
'carrot'  => '1.99',
'orange'  => '0.99',
'papaya'  => '2.99');

how do i generate a final array, that combines the two, with their common parts, that i get this final result:

   array('banana'  => '1.45',
  'apple'   => '2.99',
  'orange'  => '0.99');

3 Answers 3

5

I would use array_intersect_key() here.

$intersection = array_intersect_key($second, array_flip($first));

CodePad.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, this is what i get trying your code= Array ( [banana] => 0 [apple] => 1 [orange] => 2 ) which is not my goal here.
Check the CodePad. Make sure you have the arguments in the right order (the array of items needs to go second).
@Confidence, this should give the correct results, have you checked alex's Codepad link to see it in action?
1

You can do this:

$fruitNames = array(
'banana',
'apple',
'orange');

$fruitValues = array('banana'  => '1.45',
  'apple'   => '2.99',
  'orange'  => '0.99');



$finalArray = array();

foreach($fruitNames as $value)
{
    $finalArray[$value] = $fruitValues[$value];
}

$finalArray will have the expected value.

1 Comment

this worked fine for me, i will implement it in my rather more complex code, and keep you updated ;) thanks for now.
0

use array_key_exists to loop thru and make new array

Comments

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.