8

Im trying to add a key=>value to a existing array with a specific value.

Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:

ex:

[0] => Array
    (
        [id] => 1
        [blah] => value2

    )

[1] => Array
    (
        [id] => 1
        [blah] => value2
    )

I want to do it so that while

foreach ($array as $arr) {

     while $arr['id']==$some_id {

            $array['new_key'] .=$some value
            then do a array_push
      }    
}

so $some_value is going to be associated with the specific id.

0

3 Answers 3

13

The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:

$tmp = new array();
foreach ($array as $arr) {

     if($array['id']==$some_id) {
            $tmp['new_key'] = $some_value;
      }    
}


array_merge($array,$tmp);

A more efficient way is this:

if(in_array($some_id,$array){
  $array['new_key'] = $some_value;
}

or if its a key in the array you want to match and not the value...

if(array_key_exists($some_id,$array){
      $array['new_key'] = $some_value;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

typo: $arrary, the 'id' key exists only in $arr not in $array, and you missed the semicolon and a underline at "$some value"
7

When you use:

foreach($array as $arr){
    ...
}

... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:

foreach($array as &$arr){ // notice the &
    ...
}

... now if you add a new key to that array it will affect the $array through which you are looping.

I hope I understood your question correctly.

1 Comment

The & was the saviour
0

If i understood you correctly, this will be the solution:

foreach ($array as $arr) {
  if ($arr['id'] == $some_id) {
     $arr[] = $some value;
     // or: $arr['key'] but when 'key' already exists it will be overwritten
  }
}

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.