18

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.

2
  • You should clarify something, do you really want arr['a']='2e' at the begining, or is it a typo and you expect arr['a']=array('2e') ? Commented Aug 28, 2009 at 10:17
  • Both would do-- I don't care which is the case Commented Aug 28, 2009 at 12:59

7 Answers 7

30

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Good that it does not throw any notice/warning if key ['a'] does not exist and eventually creates that key.
14

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.

Comments

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

does exactly what you want.

Comments

0

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

Comments

0

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

Comments

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.