开发者

Compare 2 arrays for likeness

How would I compare 2 Arrays in PHP to find which values each array have in common.

Example would be

Array 1

Array
(
    [0] => ace
    [1] => one
    [2] => five
    [3] => nin开发者_运维知识库e
    [4] => elephant
)

Array 2

Array
(
    [0] => elephant
    [1] => seven
    [2] => ace
    [3] => jack
    [4] => queen
)

Output Array ( [0] => ace [1] => elephant )


array_intersect function can do this.


PHP has an array_intersect() function that can do this. As an example, ypo can put the following code into PHPFiddle for testing:

<?php
    $array1 = array('ace', 'one', 'five', 'nine', 'elephant');
    $array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');

    print_r($array1); print('<br>');
    print_r($array2); print('<br>');
    print_r(array_intersect($array1, $array2)); print('<br>');
?>

Then you'll see that it gives you what you want (reformatted for readability):

Array ( [0] => ace
        [1] => one
        [2] => five
        [3] => nine
        [4] => elephant )

Array ( [0] => elephant
        [1] => seven
        [2] => ace
        [3] => jack
        [4] => queen )

Array ( [0] => ace
        [4] => elephant ) 

Do note that this does not actually give you consecutive keys in the result, the keys appear to come from the first array given to array_intersect(). If it's important that you get a consecutively-indexed array, you may need a post-processing step to adjust it. Something like this should be a good start (modification to original fiddle to use consecutive indexes):

<?php
    $array1 = array('ace', 'one', 'five', 'nine', 'elephant');
    $array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');

    print_r($array1); print('<br>');
    print_r($array2); print('<br>');

    $array3 = array();
    foreach (array_intersect($array1, $array2) as $val) {
        array_push($array3, $val);
    }
    print_r($array3); print('<br>');
?>


If you're in a language where there is no built-in intersection, but you have hashes, you just add all the elements of one array into the hash and then go through the second array checking to see if they are in the hash you just built up.

This is all of if you don't care about order. If you care about order, it's just a for loop seeing if a[i] == b[i]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜