Oihana PHP

requireAndMergeArrays.php

Table of Contents

Functions

requireAndMergeArrays()  : array<string|int, mixed>
Requires multiple PHP files (each returning an array) and merges the results.

Functions

requireAndMergeArrays()

Requires multiple PHP files (each returning an array) and merges the results.

requireAndMergeArrays(array<string|int, mixed> $filePaths[, bool $recursive = true ]) : array<string|int, mixed>
Parameters
$filePaths : array<string|int, mixed>

An array of absolute or relative file paths to load.

$recursive : bool = true

Whether to perform a deep (recursive) merge (true) or a simple merge (false).

Tags
throws
RuntimeException

If a specified file is missing or does not return an array.

example
use function oihana\files\requireAndMergeArrays;

$paths = [
__DIR__ . '/config/default.php',
__DIR__ . '/config/override.php',
];

$config = requireAndMergeArrays($paths);
print_r($config);

Shallow merge (non-recursive):

$config = requireAndMergeArrays($paths, false);

Example of a required file:

// config/default.php
return
[
    'app' =>
    [
        'debug' => false,
        'timezone' => 'UTC',
    ],
];

// config/override.php
return
[
    'app' =>
    [
        'debug' => true,
    ],
];

Result with recursive merge:

[
    'app' =>
    [
        'debug'   => true,
        'timezone'=> 'UTC',
    ],
]

Error handling:

try
{
    $config = requireAndMergeArrays(['missing.php']);
}
catch ( RuntimeException $e )
{
    echo "Error: " . $e->getMessage();
}
author

Marc Alcaraz (ekameleon)

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

The merged array.


        
On this page

Search results