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.
PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
The array_keys() function returns an array containing the keys.
The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With