phparrayscompare

Check if two database entries are different


I'm trying to compare two entries in a database, so when a user makes a change, I can fetch both database entries and compare them to see what the user changed, so I would have an output similar to:

User changed $fieldName from $originalValue to $newValue

I've looked into this and came across array_diff but it doesn't give me the output format I need.

Before I go ahead and write a function that does this, and returns it as a nice $mtextFormatDifferenceString, can anyone point me in the direction of a solution that already does this?

I don't want to re-invent the wheel..


Solution

  • Since you require "from $originalValue to $newValue", I would go ahead and select the two rows, put them in assoc arrays, then foreach through the keys, saving the ones that aren't equal. Kind of like:

    $fields = array_keys($row1);
    $changedFields = array();
    
    foreach ($fields as $field) {
        if ($row1[$field] != $row2[$field]) {
            $changedFields[] = $field;
        }
    }
    

    I realize you were asking about the existence of pre-built wheels but I felt the solution was pretty simple.

    ?>