Find the difference of two arrays and print bidirectional changes PHP -
i have 2 arrays:
$oldvalues = array(125 => 'hello', 126 => 'bye', 131 => 'hi', 141 => ''); $newvalues = array(125 => 'hello world', 126 => 'bye', 131 => 'h', 141 => 'abc');
now explain little better, $oldvalues
holds values before user changes data on website. $newvalues
holds new values after user has saved changes.
multiple users access page @ same time, if 1 user didnt refresh page , makes changes , clicks on save want able display "hey else has updated settings before did, wanna see changes?"
, able see following output:
field changed changed 125 hello hello world 131 hi h 141 abc
note 126
not included since there no changes.
i have code using array_diff seems not work time.
$allpossiblefields = array(125, 126, 131, 141); $insertiondiff = array_diff($newvalues, $oldvalues); $deletiondiff = array_diff($oldvalues, $newvalues); $returnarray = array(); foreach($allpossiblefields $field) { if (isset($insertiondiff[$field])) { $returnarray[$field]['from'] = $oldvalues[$field]; $returnarray[$field]['to'] = $insertiondiff[$field]; } if (isset($deletiondiff[$field])) { if ( ! isset($returnarray[$field]['from'])) { $returnarray[$field]['from'] = $deletiondiff[$field]; } if ( ! isset($returnarray[$field]['to'])) { $returnarray[$field]['to'] = $newvalues[$field]; } } }
but in cases returns empty array when there difference , in cases works. know there bug somewhere in here cant seem find it.
you can make lot simpler that;
foreach($oldvalues $key => $value) { if($value != $newvalues[$key]) { echo "field " . $key . " changed " . $value . " " . $newvalues[$key] . "<br />"; } }
Comments
Post a Comment