Skip to content

Instantly share code, notes, and snippets.

@ibrahim-dogan
Last active February 26, 2021 07:52
Show Gist options
  • Save ibrahim-dogan/cc52c9aee281648be4ae1a3dd5995b0b to your computer and use it in GitHub Desktop.
Save ibrahim-dogan/cc52c9aee281648be4ae1a3dd5995b0b to your computer and use it in GitHub Desktop.
compare two array of values (nested or not) and return only changed indexes as array
<?php
/**
* It flattens multidimensional array to make arrays comparable
* then compares request with DB (usually)
* @param $request
* @param $toCompare
* @return array
* @example request: [["title" => "ABC"], ["title" => "DEF"]]
* toCompare: [["title" => "ABC"], ["title" => "XYZ"]]
* return: [1] (index 1 updated)
*/
private function findUpdatedIndexes($request, $toCompare): array
{
$flattenRequest = Arr::dot($request);
$flattenToCompare = Arr::dot($toCompare);
$updatedEntries = array_diff_assoc($flattenRequest, $flattenToCompare);
$updatedIndexes = [];
foreach ($updatedEntries as $key => $value) {
$index = explode(".", $key)[0];
$updatedIndexes[] = $index;
}
return array_unique($updatedIndexes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment