Created
April 26, 2016 07:54
-
-
Save OutOfBrain/00b2e6ba9bd1924e8b5a983cbfc0c42e to your computer and use it in GitHub Desktop.
Intersect arrays recursively in php.
This file contains hidden or 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 | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, perfect