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 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.

Answers


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 />";
    }
}

Need Your Help

Official Twitter follow button code does not pass validator

html twitter validation twitter-follow

I ran my website through Validator and it returned two errors, both of which relating to the official Twitter follow button code.

How to change to Year Month Week format?

r

I have dates in year month day format that I want to convert to year month week format like so:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.