You are viewing our old blog site. For latest posts, please visit us at the new space. Follow our publication there to stay updated with tech articles, tutorials, events & more.

array_merge behaving differently on 32-bit and 64-bit architecture

0.00 avg. rating (0% score) - 0 votes

PHP has a large number of functions one of which commonly used is array_merge.¬†It basically merges¬†‘n’ number of arrays. We have used it quite often in my code and found out that it does not preserve keys when moved from 32-bit architecture to 64-bit.

Let’s figure out why this happened ?
Recently We moved our ubuntu servers from 32-bit to 64-bit. Then suddenly some of arrays started losing their indexes which were working on previous server. Then we figured out it was an issue with array_merge. Code was using big numbers as indexes in multiple arrays which needs to be merged. Here is a sample of code.
<?php
  $array1 = array(
      '1293890131293' => '....somedata...',
      '9234809839103' => '...moredata....'
    );
    
  $array2 = array(
      '1298923904234' => '...somemoredata'
  );
  

On the previous servers the output was :

<?php
  $result = array(
      '1293890131293' => '....somedata...',
      '9234809839103' => '...moredata....',
      '1298923904234' => '...somemoredata'
  );

But after the migration, the scenario was :

<?php
  $result = array(
      0 => '....somedata...',
      1 => '...moredata....',
      2 => '...somemoredata'
  );
After this happened, We tried to figure out how array_merge works. Actually the function merge only preserves keys if the indexes does not fall in the range of integers, i.e. if the keys are integers in php, then indexes would reset and start from 0,1,2…. Since in 32-bit architecture the integer max value is
231 = 2147483648
and the values were out of bound, so keys were preserved in the system. But when We tried the same with the 64-bit architecture where the maximum integer value is way too much
263 = 9223372036854775807
then the array indexes were considered as numbers and the function vanished the older indexes to create newer ones. So to fix this, We replaced array_merge with ¬†‘+’ operator . But there are still restrictions with ‘+’ operator as it doesn’t save duplicate array indexes and also doesn’t work for associate arrays. So We would recommend you writing a custom merging function if you are stuck in such a scenario. Also, it is important to ensure what the function is doing, before using it, if you are not having any prior knowledge about it.
Happy Coding!
Tags: , , ,