Skip to content

diff()

Structural diff between two JSON documents.

Signature

php
JsonFast::diff(
    string $before,
    string $after,
    ?int $output = OUTPUT_ARRAY
): mixed

Parameters

NameTypeDefaultDescription
$beforestringOriginal JSON
$afterstringUpdated JSON
$output?intOUTPUT_ARRAYOutput mode

Returns

FieldDescription
addedPaths present only in $after (JSON Pointer-style keys, e.g. $.role)
removedPaths present only in $before
changedPaths in both with different values — each entry has from and to

Example return value

php
$changes = JsonFast::diff(
    '{"name":"Allan","active":true}',
    '{"name":"Allan","active":false,"role":"admin"}'
);
/*
[
    'added' => ['$.role' => 'admin'],
    'removed' => [],
    'changed' => [
        '$.active' => ['from' => true, 'to' => false],
    ],
]
*/

Examples

Audit log for config updates:

php
$changes = JsonFast::diff($previousConfig, $newConfig);

foreach ($changes['changed'] as $path => $delta) {
    audit()->info("Config changed: $path", $delta);
}

Detect drift between stored and live API responses:

php
$drift = JsonFast::diff($cachedResponse, $liveResponse);
$hasDrift = !empty($drift['added']) || !empty($drift['removed']) || !empty($drift['changed']);

Performance

Roughly 3.3× faster than native PHP diff helpers in project benchmarks — see benchmarks.

Native tools, weird experiments, and practical performance work.