Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: append to value if the key already exist, if not add the key

Tags:

arrays

php

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.

like image 523
Graviton Avatar asked Aug 28 '09 10:08

Graviton


People also ask

How do you check if a key exists in an array in PHP?

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.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is Array_push in PHP?

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).


1 Answers

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);
like image 81
FlorianH Avatar answered Nov 12 '22 00:11

FlorianH