Skip to content

Instantly share code, notes, and snippets.

@sanchezzzhak
Created April 15, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanchezzzhak/e02addfba530f99d310fa5931c6a7617 to your computer and use it in GitHub Desktop.
Save sanchezzzhak/e02addfba530f99d310fa5931c6a7617 to your computer and use it in GitHub Desktop.
Compare 2 arrays values $old and $new and return array [ new values, unchanged values, deleted values]
<?php
/**
* Class MiscHelper
* @package app\helpers
*/
class MiscHelper
{
/**
* ```php
* list($create, $update, $delete) = MiscHelper::diff([25, 33 ], [ 25, 55, 57 ]);
* var_dump($create) // [55, 57]
* var_dump($update) // [25]
* var_dump($delete) // [33]
* ```
*
* Compare 2 arrays values $old and $new and return array [ new values, unchanged values, deleted values]
* @param array $old
* @param array $new
* @return array
*/
public static function diff(array $old, array $new): array
{
$new = array_flip($new);
$old = array_flip($old);
$update = array_intersect_key($old, $new);
$delete = array_diff_key($old, $update);
$create = array_diff_key($new, $update);
return [array_keys($create), array_keys($update), array_keys($delete)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment