Skip to content

Instantly share code, notes, and snippets.

@OutOfBrain
Created April 26, 2016 07:54
Show Gist options
  • Save OutOfBrain/00b2e6ba9bd1924e8b5a983cbfc0c42e to your computer and use it in GitHub Desktop.
Save OutOfBrain/00b2e6ba9bd1924e8b5a983cbfc0c42e to your computer and use it in GitHub Desktop.
Intersect arrays recursively in php.
<?php
class Interect
{
/**
* Return intersecting array of varargs arrays.
* Compares keys and values. Checks recursively.
* Returns empty array if no intersection.
*
* @param array ...$arrays
* @return array
*/
public static function intersectRecursiveAll(array ...$arrays)
{
$intersect = array_shift($arrays);
for ($i = 0, $len = count($arrays); $i < $len; ++$i) {
$intersect = self::intersectRecursive($intersect, $arrays[$i]);
}
return $intersect;
}
/**
* Return intersecting array of two given arrays.
* Compares keys and values. Checks recursively.
* Returns empty array if no intersection.
*
* @param array $array1
* @param array $array2
* @return array
*/
public static function intersectRecursive($array1, $array2)
{
$properties = [];
foreach ($array1 as $key => $value) {
if (isset($array2[$key])) {
// key the same - check value
$value1 = $value;
$value2 = $array2[$key];
if (is_array($value1)) {
$intersectValue = self::intersectRecursive($array1[$key], $array2[$key]);
if ($intersectValue) {
$properties[$key] = $intersectValue;
}
} elseif ($value1 === $value2) {
$properties[$key] = $value1;
}
}
}
return $properties;
}
}
@mgerasimchuk
Copy link

thanks, perfect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment