Question

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 to explain this little better, $oldValues holds the values before user changes any data on website. $newValues holds the new values after user has saved the changes.

Multiple users access the page at the same time, so if one user didnt refresh the page and makes any changes and clicks on save I want to be able to display that "Hey someone else has updated this settings before you did, wanna see the changes?" and they are able to see the following output:

Field        Changed From          Changed To
125          hello                 hello world
131          hi                    h
141                                ABC

note that 126 is not included since there were no changes.

I already have code using array_diff but it seems not to work all the time.

$allPossibleFields = array(125, 126, 131, 141);
$insertionDiff = array_diff($newValues, $oldValues);
$deletionDiff  = array_diff($oldValues, $newValues);

$returnArray = array();
foreach($allPossibleFields as $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 some cases it returns empty array when there is a difference and in some cases it works. I know there is a bug somewhere in here but cant seem to find it.

Was it helpful?

Solution

You can make it a lot simpler than that;

foreach($oldValues as $key => $value) {
    if($value != $newValues[$key]) {
        echo "Field " . $key . " was changed from " . $value . " to " . $newValues[$key] . "<br />";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top