Graviton
Graviton

Reputation: 83254

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

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.

Upvotes: 18

Views: 37379

Answers (7)

VoteyDisciple
VoteyDisciple

Reputation: 37803

There are three situations:

  1. The key is undefined
  2. The key is defined, but isn't yet set to an array
  3. The key is defined, and the element is an array.

So, in code:

function appendThings(/* map[string,mixed] */ $array, /* string */ $key, /* string */ $value) {
    if (!isset($array[$key]))
        $array[$key] = $value;
    else if (is_array($array[$key]))
        $array[$key][] = $value;
    else
        $array[$key] = array($array[$key], $value);

    return $array;
}

It's only the last case that's tricky: if it's not an array yet, you'll need to compose one using the current value plus the new one.

Upvotes: 14

Quamis
Quamis

Reputation: 11077

Strictly array:

$arr['a']=(is_array($arr['a'])? '2e' : array_merge(Array('2e'),$arr['a']));

String with separators:

$arr['a'].='2e'.'/'; // '/' is used as a separator in here.

if you need the string as an array just do $arr['a'] = explode("/",$arr['a']);

both methods are ugly... you should try, as FlorianH suggested, to use the whole variable as an array.

Another method might be to use the Interface in PHp and build something that make suse of the Iterator and ArrayAccess interfaces. (https://www.php.net/manual/en/class.iterator.php, https://www.php.net/manual/en/class.arrayaccess.php)

Upvotes: 0

n1313
n1313

Reputation: 21381

if (isset($array[$key]) {
  if (!is_array($array[$key]))
    $array[$key] = (array)$array[$key];
  $array[$key][] = $new_value;
} else {
  $array[$key] = $new_value;
}

Something like that? You can surely simplify this by adding first value as an one-element array, or by using ternar operators, but anyway you'll need a custom function to do the job.

Upvotes: 0

Amber
Amber

Reputation: 526573

function update_keypair($arr, $key, $val)
{
   if(empty($arr[$key])) $arr[$key] = array($val);
   else $arr[$key][] = $val;
}

does exactly what you want.

Upvotes: 3

mck89
mck89

Reputation: 19231

Try this

$key="a";
$value="b";
$array=array();

if(!array_key_exists($key,$array)) $array[$key]=$value;
elseif(is_array($array[$key]))$array[$key][]=$value;
else $array[$key]=array($array[$key],$value);

Upvotes: 0

FlorianH
FlorianH

Reputation: 3102

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

Upvotes: 30

RaYell
RaYell

Reputation: 70414

You need to write a function that does that. Or initialize your first element as an array as well and use array_push function to add new elements.

$a = array('2e');
array_push($a, '45');
array_push($a, 'gt');

Upvotes: 0

Related Questions