Skip to content

Instantly share code, notes, and snippets.

@danielm
Last active June 14, 2024 23:23
Show Gist options
  • Save danielm/16deed81ba7bfb6f171b6fc3b1856966 to your computer and use it in GitHub Desktop.
Save danielm/16deed81ba7bfb6f171b6fc3b1856966 to your computer and use it in GitHub Desktop.
Find differences between two Arrays of strings in PHP
<?php
function findDifferences(array $array1, array $array2)
{
// Elements present in array1 but not in array2
$missingInArray2 = array_diff($array1, $array2);
// Elements present in array2 but not in array1
$addedInArray2 = array_diff($array2, $array1);
// Elements common in both arrays
$commonElements = array_intersect($array1, $array2);
// Check for rearranged elements by comparing positions
$rearrangedElements = [];
foreach ($commonElements as $element) {
$posArray1 = array_search($element, $array1);
$posArray2 = array_search($element, $array2);
if ($posArray1 !== $posArray2) {
$rearrangedElements[$element] = [
'from' => $posArray1,
'to' => $posArray2
];
}
}
return [
'missing' => $missingInArray2,
'added' => $addedInArray2,
'rearranged' => $rearrangedElements
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment