Merging associative arrays in PHP
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
- mapping m1 = ([ "key1" : "Value 1", "key2" : "Value 2" ]);
- mapping m2 = ([ "key3" : "Value 3" ]);
- write("My mapping: %O\n", m1 + m2);
- //> My mapping: ([ /* 3 elements */
- //> "key1": "Value 1",
- //> "key2": "Value 2",
- //> "key3": "Value 3"
- //> ])
And I noted that I had done the same thing in PHP and the result was perfectly valid:
- $a1 = array("key1" => "Value 1", "key2" => "Value 2");
- $a2 = array("key3" => "Value 3");
- echo "My mapping: ";
- print_r($a1 + $a2);
- //> My mapping: Array
- //> (
- //> [key1] => Value 1
- //> [key2] => Value 2
- //> [key3] => Value 3
- //> )
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!


