Oihana PHP

merge.php

Table of Contents

Functions

merge()  : array<string|int, mixed>
Merges two arrays using MergeOption normalized settings.

Functions

merge()

Merges two arrays using MergeOption normalized settings.

merge(array<string|int, mixed> $original, array<string|int, mixed> $external[, array<string|int, mixed> $options = [] ]) : array<string|int, mixed>

This function provides a flexible way to merge arrays, supporting:

  • Deep recursive merging of nested arrays.
  • Indexed sub-array storage for multiple values.
  • Unique value enforcement in lists.
  • Configurable handling of null values ('skip', 'keep', 'overwrite').
  • Optional cleaning of the result using CleanFlag constants.
Parameters
$original : array<string|int, mixed>

The original array to merge into.

$external : array<string|int, mixed>

The array whose values will be merged into the original.

$options : array<string|int, mixed> = []

Optional MergeOption array to control merge behavior.

Tags
example
use oihana\core\arrays\merge;
use oihana\core\options\MergeOption;
use oihana\core\arrays\CleanFlag;

$a =
[
   'users' =>
    [
        ['name' => 'Alice'],
        ['name' => 'Bob']
    ],
    'count' => 2,
];

$b =
[
    'users' =>
    [
        ['name' => 'Charlie'],
        ['name' => 'Alice'],
   ],
   'count' => null,
   'extra' => null,
];

// Deep merge, skip nulls, keep unique users, clean result
$result = merge( $a , $b ,
[
    MergeOption::DEEP   => true ,
    MergeOption::UNIQUE => true ,
    MergeOption::NULLS  => 'skip' ,
    MergeOption::CLEAN  => CleanFlag::DEFAULT
]);

// Result:
// [
//     'users' => [
//         ['name' => 'Alice'],
//         ['name' => 'Bob'],
//         ['name' => 'Charlie']
//     ],
//     'count' => 2
// ]
author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
array<string|int, mixed>

The merged array, optionally cleaned according to CleanFlag.


        
On this page

Search results