gonna_take_sometime
gonna_take_sometime

Reputation: 75

Updating any value in multi-dimensional arrays

I'm trying to update values in a multi-dimensional array (using a function so it can be done dynamically), but my approach of looping through each values doesn't seem to work. I tried different solutions offered on stackoverflow but I still can't seem to make it work as a function (with dynamic keys). Here is a simple example with a 2 level array, but it should work on any level.

function updateArrayValue($array,$key_to_find,$new_value){
  foreach($array as $key => $value){
    if($key == $key_to_find){
      $value = $new_value;
      break; // Stop the loop
    }
  }
  return $array;
}

$array = array("001"=>"red", "002"=>"green", "003"=>array("003-001"=>"blue", "003-002"=>"yellow"));

$array = updateArrayValue($array,"003-001","purple");
var_dump($array);

Upvotes: 0

Views: 56

Answers (1)

daremachine
daremachine

Reputation: 2788

You need recursion call of function and set new values. Not value only but changed deep array.

  function updateArrayValue($array,$key_to_find,$new_value){
      foreach($array as $key => $value){
        // if value is not an array then try set new value if is search key
        if(!is_array($value)){
            if($key == $key_to_find) {
                $array[$key] = $new_value;
            }
        }
        else {
            // otherwise call function again on value array
            $array[$key] = updateArrayValue($value, $key_to_find, $new_value);
        }
      }
      return $array;
    }

    $array = array(
      "001"=> "red",
      "002"=> "green", 
      "003"=> array(
         "003-001"=> "blue",
         "003-002"=> "yellow"
      ));

    $newArray = updateArrayValue($array,"003-001","purple");
    var_dump($newArray);

Upvotes: 1

Related Questions