array manipulation

nested_array_merge_deep.php
use Drupal\Component\Utility\NestedArray;

// Parent array with default settings.
$parent_array = [
    'config' => [
        'theme' => 'dark',
        'layout' => [
            'width' => 800,
            'height' => 600,
        ],
    ],
];

// Child array adds more nested data but doesn't override existing values.
$child_array = [
    'config' => [
        'layout' => [
            'depth' => 300, // New nested key
        ],
        'features' => [
            'animations' => true, // New section
        ],
    ],
];

// Merge both arrays.
$merged_array = NestedArray::mergeDeep($parent_array, $child_array);
nested_array_result.php
[
    'config' => [
        // Unchanged (not overridden)
        'theme' => 'dark', 
        'layout' => [
            // Keeps parent value
            'width' => 800, 
            // Keeps parent value  
            'height' => 600,
            // New nested key added
            'depth' => 300,   
        ],
        'features' => [
            // New section added
            'animations' => true, 
        ],
    ],
]
30.07.2026 | Lothar Ferreira Neumann

Merge multidimensional arrays in Drupal

array_shuffle.php
$array = [
  'key_one' => 'one',
  'key_two' => 'two',
  'key_three' => 'three',
];
onlyKeys.php
// You will get a mixed array with only keys or values, depends if you use array_flip()

// Change keys to values and vice versa.
array_flip($array);

// Reduce the array to the keys and shuffle them.
array_rand($array);
shuffledArray.php
// Array will be shuffled with key => value staying a pair.

// Shuffle the key => value array, keeping both.
shuffle($array);
04.04.2024 | Lothar Ferreira Neumann

Mix values of an associated array