Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a value in a multidimensional array given the indexes of value

I have an array that contains the location of a value in a very large multidimensional array. I need to take this location and replace the value at the location with another value. I have found numerous articles about returning the value of a position using such an array of indexes by writing a recursive function. However, this won't work because I can't slice up the large array, I need to replace just that one value.

The location would look something like:

array(1,5,3,4,6);

The code I had to find a value is the following:

function replace_value($indexes, $array, $replacement){
    if(count($indexes) > 1)
        return replace_value(array_slice($indexes, 1), $array[$indexes[0]], $replacement);
    else
        return $array[$indexes[0]];
    }
}

How would I modify this to instead of recursively cutting down an array until the value is found I can simply modify a part of a large array? Is there a way to build

array(1,5,3,4,6);

Into

$array[1][5][3][4][6];

Thanks

like image 989
Chris Avatar asked Jan 16 '23 17:01

Chris


1 Answers

You could modify your function like this:

function replace_value($indexes, &$array, $replacement){
    if(count($indexes) > 1) {
        return replace_value(array_slice($indexes, 1), $array[$indexes[0]], $replacement);
    } else {
        return $array[$indexes[0]] = $replacement;
    }
}

Make sure your write &$array in the function definition, not $array This will pass in the actual array, so that you can modify it in place. Otherwise you would just be passing in a copy.

like image 150
declan Avatar answered Jan 25 '23 16:01

declan