function DiffArray::diffAssocRecursive

Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Component/Utility/DiffArray.php \Drupal\Component\Utility\DiffArray::diffAssocRecursive()
  2. 10 core/lib/Drupal/Component/Utility/DiffArray.php \Drupal\Component\Utility\DiffArray::diffAssocRecursive()
  3. 11.x core/lib/Drupal/Component/Utility/DiffArray.php \Drupal\Component\Utility\DiffArray::diffAssocRecursive()

Recursively computes the difference of arrays with additional index check.

This is a version of array_diff_assoc() that supports multidimensional arrays.

Parameters

array $array1: The array to compare from.

array $array2: The array to compare to.

Return value

array Returns an array containing all the values from array1 that are not present in array2.

3 calls to DiffArray::diffAssocRecursive()
DiffArrayTest::testDiffAssocRecursive in core/tests/Drupal/Tests/Core/Common/DiffArrayTest.php
Tests DiffArray::diffAssocRecursive().
HTMLRestrictions::doDiff in core/modules/ckeditor5/src/HTMLRestrictions.php
Computes difference of two HTML restrictions, without wildcard support.
Link::compare in core/modules/jsonapi/src/JsonApiResource/Link.php
Compares two links.

File

core/lib/Drupal/Component/Utility/DiffArray.php, line 27

Class

DiffArray
Provides helpers to perform diffs on multi dimensional arrays.

Namespace

Drupal\Component\Utility

Code

public static function diffAssocRecursive(array $array1, array $array2) {
    $difference = [];
    foreach ($array1 as $key => $value) {
        if (is_array($value)) {
            if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
                $difference[$key] = $value;
            }
            else {
                $new_diff = static::diffAssocRecursive($value, $array2[$key]);
                if (!empty($new_diff)) {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.