1

someone know a function how to get before and after things of array_diff.

var_dump(array_diff(['a' => 'b', 'c' => 'x'], ['a' => 'c', 'c' => 'x']));

Result is

array(1) {
  'a' =>
  string(1) "b"
}

And i want something like

array(2) {
  [0] =>
  array(1) {
    'a' =>
    string(1) "b"
  }
  [1] =>
  array(1) {
    'a' =>
    string(1) "c"
  }
}

Is there a function for that or have you some snippet for it?

Thanks in Advance!

0

2 Answers 2

1

Try using array_diff_assoc - array_diff only compares values.

You could do something like this:

$arr1 = ['a' => 'b', 'c' => 'x'];
$arr2 = ['a' => 'c', 'c' => 'x'];

$diffs = [
    array_diff_assoc($arr1, $arr2),
    array_diff_assoc($arr2, $arr1)
];
Sign up to request clarification or add additional context in comments.

1 Comment

Ah thanks but i see that it not work with array in array. (Recursive diff) But i think i saw a recursive array_diff last days. Or do you have a solution for that? I mean that was something with array_map.
1

Try this: You can diffirentiate there keys because after your array are keys of arrays

 $newArr = [
  ['a' => 'b', 'c' => 'x'],
  ['a' => 'c', 'c' => 'x']
 ];

$a = array_diff_assoc($newArr[0], $newArr[1]); //differentiate the 1st and 2nd keys
$b = array_diff_assoc($newArr[1], $newArr[0]); //differentiate the 2nd keys to the 1st keys
$diff = [$a, $b]; //then store the result to an array

echo '<pre>';
var_dump($diff);

Here's the output:

 array(2) {
   [0]=>
    array(1) {
     ["a"]=>
     string(1) "b"
    }
   [1]=>
    array(1) {
     ["a"]=>
     string(1) "c"
   }
 }

Or if it is a array of array:

 //all keys are 0 and 1 because you're differentiate only two keys in one multi-dimensional array

$arr2= [
   0 => [
     ['a' => 'b', 'c' => 'x'],
     ['a' => 'c', 'c' => 'x']
   ],
   1 => [
     ['d' => 'e', 'c' => 'y'],
     ['d' => 'b', 'c' => 'y']
   ]
];

foreach($arr2 as $key => $val){
  $a[] = array_diff_assoc($val[0], $val[1]);
  $b[] = array_diff_assoc($val[1], $val[0]);
 }
 var_dump($diff);

Output:

array(2) {
 [0]=>
  array(2) {
    [0]=>
     array(1) {
       ["a"]=>
       string(1) "b"
     }
    [1]=>
     array(1) {
      ["d"]=>
      string(1) "e"
     }
    }
  [1]=>
    array(2) {
     [0]=>
      array(1) {
       ["a"]=>
       string(1) "c"
      }
     [1]=>
      array(1) {
       ["d"]=>
       string(1) "b"
      }
   }
} 

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.