0

I am trying to compare two array value. My array1 is like

$a1 = array('123' => 'test1', '456' => 'test2', '789' => 'test3');

array2 is like

$a2 = array('456' => 'match2', '99' => 'match3');

$a3 = array();

I want to compare the key value. If array1 key matches array2 key, push array1 element to a new array

I have

  for($i=0; $i < count($a1); $i++){
       //i am not sure how to write my codes heree......
        if($a1[$i]==a2[$i]{
            $a3[]=a1$[$i];
        }
    }

Can someone help me out on this? Thanks a lot!

2
  • 5
    have you looked at array_intersect_key()? Commented Sep 30, 2013 at 15:52
  • 1
    Beginning to think I should start posting my answers in the comment section instead. Commented Sep 30, 2013 at 16:06

3 Answers 3

2

You can use array_intersect_key http://www.php.net/manual/en/function.array-intersect-key.php

Code:

$a1 = array('123' => 'test1', '456' => 'test2', '789' => 'test3');

$a2 = array('456' => 'match2', '99' => 'match3');

$a3 = array_values(array_diff_key($a1, $a2));

print_r($a3);

Output:

Array
(
    [0] => test1
    [1] => test3
)

This is what you are after right? It should be faster than a for loop since it's a native PHP function.

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

1 Comment

try to elaborate a little bit more the answer, instead of just the link, write some code :)
0

This should work, though I haven't tested it

foreach ($a1 as $k1 => $v1) {
   if (isset($a2[$k1]))
      $a3[$k1] = $v1;
}

You loop through all the elments of $a1 and check if that key exists in $a2. If it does you add the element to $a3 (the code above adds it with the existing key, if you want to discard the keys, just use $a3[] = $v1;)

Comments

0
$a1= array('123' => 'test1', '456' => 'test2', '789' => 'test3');
$a2=array('456' => 'match2', '99' => 'match3');
$ai = array_intersect_key($a1, $a2);
$a3 = array_values($ai);

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.