0

Consider I have associative array with same key values:

$arr = {'MessageID' =>1 ,'MessageID' =>5 , 'MessageID' => 8};

Now I want every call to function foo() which will insert a new key value of 'MessageID'=>integer

How can we do that without overriding other existing key values pairs?

2
  • 1
    possible duplicate of stackoverflow.com/questions/5445283/… AFAIK, the array keys can't be duplicated, so the question is, how you ended up with the sample array you gave use... Commented Aug 12, 2014 at 9:41
  • You cannot have duplicate keys in an array. Also your sample with curly braces is not valid php syntax. Please clarify Commented Aug 12, 2014 at 9:44

4 Answers 4

1

As many answerers before, you can't have keys with the same string in the array in PHP. If you want to represent multiple values per key I use something like this:

$arr = ['MessageID' => [1, 5, 8]];

You would append to MessageID with this code:

$arr['MessageId'][] = 10;

Then it would look like this:

['MessageID' => [1, 5, 8, 10]]

This worked well for me with HTTP headers and other things which are key value based, but can have multiple values.

Sign up to request clarification or add additional context in comments.

Comments

1

In php array, you can not insert multiple values with same index. If you want to use it then you can use it with following manner

$MessageID = array(1,5,8); and $MessageID[] = $newValue; to insert new value.

Comments

1

You cannot have an array with duplicate keys.

A better implementation would be to have an array called $messageIDs and save the actual values in the array:

$messageIDs = array (1, 5, 8);

Comments

1

As i mentioned in comments, you cannot have duplicate keys in an array. Also your sample with curly braces is not valid php syntax.

Perhaps you need a multidimentional array:

$arr = [['messageID'=>1],['messageID'=>5],['messageID'=>8]];

in which case you would add another value like so:

$arr[] = ['messageID'=>11];

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.