Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding key=>value pair to existing array with condition

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.

like image 779
Yeak Avatar asked Jul 12 '12 22:07

Yeak


1 Answers

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;
    }
like image 127
Tucker Avatar answered Nov 26 '22 01:11

Tucker