PHP: append to value if the key already exist, if not add the key
arrays, php
Solution
You could solve the problem, by using an array for the first element ("2e") aswell:
$arr = array();
$arr['a'][] = '2e';
$arr['a'][] = '45';
$arr['a'][] = 'gt';
print_r($arr);
Problem
I am looking for a succinct way of doing this in PHP: given an array, if I add one `key=>value` pair to it, the routine should check whether the key already exist. If it doesn't exist, add to the array with the `key=>value` pair. If it does, then the value should be append to the value of the array. So, for example, if the initial array is this ``` arr['a']='2e' ``` When I add a `'a'=>'45'` pair to the array, then the routine will return me ``` arr['a']=array('2e', '45') ``` When I add another `'a=>gt'` pair to it, then the routine will return me ``` arr['a']=array('2e', '45','gt') ``` Is there a succinct way of doing this? Of course I can write it myself but I believe my solution is very ugly.