Last active
August 29, 2015 14:04
-
-
Save mohrt/f7ea4e2bf2ec8ba7542c to your computer and use it in GitHub Desktop.
php: compute differences (inserts, updates, deletes) between two associative arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* compute differences between associative arrays. | |
* the inserts, updates, deletes are returned | |
* in separate arrays. Note: To combine arrays | |
* safely preserving numeric keys, use $a + $b | |
* instead of array_merge($a, $b). | |
* | |
* Author: Monte Ohrt <monte@ohrt.com> | |
* Version: 1.0 | |
* Date: July 17th, 2014 | |
* | |
* @param array $a1 | |
* @param array $a2 | |
* @return array ($inserts, $updates, $deletes) | |
*/ | |
get_array_differences($a1, $a2) { | |
// get diffs forward and backward | |
$forward = array_diff_assoc($a1, $a2); | |
$backward = array_diff_assoc($a2, $a1); | |
// compute arrays | |
$inserts = array_diff_key($forward, $backward); | |
$updates = array_intersect_key($forward, $backward); | |
$deletes = array_diff_key($backward, $forward); | |
return array($inserts, $updates, $deletes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment