Search code examples
phparraysobjectserializationstrcmp

PHP: `strcmp` serialization of identical object and array failing


I have a legacy app where i am trying to migrate changes from the old into the new while generating a log of changes. Things are going well; however, I keep running into "changes" that change nothing. After digging into this, I found that the legacy code is using arrays and the new code is using objects. If serialized, I thought they would be identical. After all, if they are dumped via print_r they are identical. But that is not the case. Even more astounding, the objects keep their integer keys even after serialize-unserialize cycling them.

The request is: how can I show these two strings are identical since their resulting object/array is identical save for key typing.

<?php
  $v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
  $v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
  $v3 = unserialize($v3v);
  $v4 = unserialize($v4v);
  die('<pre>'.print_r($v3,true).' '.print_r($v4,true));

outputs (the identical):

Array ( [lastindex] => 1 [1] => 1 ) Array ( [lastindex] => 1 [1] => 1 )

so let's now bring them "back to life":

$v3v = serialize($v3);
$v4v = serialize($v4);
die('<pre>'.print_r($v3v,true).PHP_EOL.print_r($v4v,true));

whaaa? how did you remember your integer keys??"

a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}
a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}

and how can i get you to stop???


Solution

  • You can use array_diff instead of strcmp. You can try this -

      $v3v = 'a:2:{s:9:"lastindex";s:1:"1";i:1;s:1:"1";}';
      $v4v = 'a:2:{s:9:"lastindex";i:1;i:1;s:1:"1";}';
      $v3 = unserialize($v3v);
      $v4 = unserialize($v4v);
      echo empty(array_diff($v3, $v4)) ? 'Identical' : 'Not Identical';
    

    array_diff($v3, $v4) will return empty array if they are indentical.

    Working code