减去数组以获得每个差异

What I have

$array1 = [1,1,1];
$array2 = [1,1];

What I'm doing:

array_diff( $array1, $array2 );

What I expected:

array(1) { 1 }

What I got

array(0) { }

How do I subtract two arrays to get every discrepancy?


Edit: My example was incomplete, sorry.

If we also have values like this:

$array1 = [1,1,2,1];
$array2 = [1,1,1,2];

I would expect

[1,1,2,1] - [1,1,1,2] = []

array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().

So this should work for you:

<?php

    $array1 = [1,1,2,1];
    $array2 = [1,1,1,2];

    function caseCmpSort($a, $b){
        return strcasecmp($a, $b);  
    }

    usort($array1, "caseCmpSort");
    usort($array2, "caseCmpSort");

    $result = array_diff_assoc($array1, $array2);

    print_r($result);

?>

output:

Array ( )

So you should check array key differences too. Have you tried array_diff_assoc()?

http://php.net/manual/en/function.array-diff-assoc.php

From manual:

Returns an array containing all the entries from array1 that are not present in any of the other arrays. 

So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.

$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));

Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.

$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));

use array_diff_assoc

$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)

try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb

<?php
$n = array(1,1,1);

$m = array(1,1);

$r = array_diff_assoc($n,$m);
var_dump($r);
?>