Merging associative arrays in PHP

Published 20 October, 2009 in Programming - 0 Comments

It’s nice when serendipity is your friend! I was porting my Bitly class from Pike to PHP – I know there’s probably a hundred PHP classes already out there, but mine is better coded ;) – and noted by accident that I had used some Pike syntax in my PHP class but it was working anyway. So what was I doing? In Pike there’s separate data type for associative arrays called mapping. In Pike, in general, when merging two objects you just join them with a + sign. Thus merging two mappings you do like

9 lines of Pike
  1. mapping m1 = ([ “key1” : “Value 1”, “key2” : “Value 2” ]);
  2. mapping m2 = ([ “key3” : “Value 3” ]);
  3. write(“My mapping: %O\n”, m1 + m2);
  4. //> My mapping: ([ /* 3 elements */
  5. //> “key1”: “Value 1”,
  6. //> “key2”: “Value 2”,
  7. //> “key3”: “Value 3”
  8. //> ])

And I noted that I had done the same thing in PHP and the result was perfectly valid:

11 lines of PHP
  1. $a1 = array(“key1” => “Value 1”, “key2” => “Value 2”);
  2. $a2 = array(“key3” => “Value 3”);
  3. echo “My mapping: “;
  4. print_r($a1 + $a2);
  5. //> My mapping: Array
  6. //> (
  7. //> [key1] => Value 1
  8. //> [key2] => Value 2
  9. //> [key3] => Value 3
  10. //> )

This method doesn’t work on flat array though so there you’ll still have to use array_merge(), but pretty nice anyway.

And oh, the PHP Bitly class will be part of the new PLib release once done!