[PHP-NOTES] note 130634 added to function.array-diff-assoc

[email protected] ("[email protected]") Mon, 02 Feb 2026 23:31:59 +0000
Newsgroups php.notes
Message-ID <[email protected]>
Handy function to compare value changes between arrays, based on array_diff_assoc().
Valid for PHP 7.4+ due to the use of arrow functions as a shorthand, but may be "downgraded" as well.

<?php

function array_changes($amDataOld, $amDataNew)
{
    $fnDiffGroup = fn ($sDiffKey) => [
        'old' => ($amDataOld[$sDiffKey] ?? NULL),
        'new' => ($amDataNew[$sDiffKey] ?? NULL),
    ];

	$asDataOld  = array_map('serialize', $amDataOld);
    $asDataNew  = array_map('serialize', $amDataNew);
    $asDiffKeys = array_keys(
            array_diff_assoc($asDataOld, $asDataNew)
        +   array_diff_assoc($asDataNew, $asDataOld)
    );
    
    return array_combine($asDiffKeys, array_map($fnDiffGroup, $asDiffKeys));
}

$a1 = [
    'SameValue'       => 230.0,
    'SameArray'       => ['foo' => 'FOO', 'bar' => 'BAR'],
    'DiffValue'       => 48.25,
    'DiffTypeSimple'  => 100.1,
    'DiffTypeComplex' => 27.8,
    'DiffTypeArray'   => ['foo' => 'FOO', 'bar' => 'BAR'],
];
$a2 = [
    'SameValue'       => 230.0,
    'SameArray'       => ['foo' => 'FOO', 'bar' => 'BAR'],
    'DiffValue'       => 41.5,
    'DiffTypeSimple'  => '100.1',
    'DiffTypeComplex' => ['foo' => 'FOO', 'bar' => 'BAZ'],
    'DiffTypeArray'   => ['foo' => 'FOO', 'bar' => 'BAZ'],
];

var_dump(array_changes($a1, $a2));

?>
----
Server IP: 206.189.2.9
Probable Submitter: 77.24.107.73
----
Manual Page -- https://php.net/manual/en/function.array-diff-assoc.php
Edit        -- https://main.php.net/note/edit/130634
Del: integrated  -- https://main.php.net/note/delete/130634/integrated
Del: useless     -- https://main.php.net/note/delete/130634/useless
Del: bad code    -- https://main.php.net/note/delete/130634/bad+code
Del: spam        -- https://main.php.net/note/delete/130634/spam
Del: non-english -- https://main.php.net/note/delete/130634/non-english
Del: in docs     -- https://main.php.net/note/delete/130634/in+docs
Del: other reasons-- https://main.php.net/note/delete/130634
Reject      -- https://main.php.net/note/reject/130634
Search      -- https://main.php.net/manage/user-notes.php