How to dynamically set value in multidimensional array by reference
multidimensional-array, pass-by-reference, php
Solution
You can try
$data = array();
$keys = array(
0 => 'should',
1 => 'be',
2 => 'int'
);
$value = 'yjd';
echo "<pre>";
setValue($data,$keys,$value);
print_r($data);
Output
Array
(
[should] => Array
(
[be] => Array
(
[int] => yjd
)
)
)
Function Used
function setValue(&$data, $path, $value) {
$temp = &$data;
foreach ( $path as $key ) {
$temp = &$temp[$key];
}
$temp = $value;
return $value ;
}
Problem
This has been driving me nuts all evening. Basically, I need to set a specific value in a multidimensional array after sanitizing the value and then again (maybe, depends on validation; if validation failed then the value needs to be set to an empty string) after validating the value. Let's say I have this post array: ``` $data['should']['be']['int'] = ' yjd'; ``` After sanitizing the value with `filter_var( $value, FILTER_SANITIZE_NUMBER_INT );` I'm getting an empty string back. I would then need to somehow set the value on `$data['should']['be']['int']` to be an empty string. This value then gets passed to a validation function, which fails, cause the empty string is not an integer. Again, that validated value would then need to get set in `$data['should']['be']['int']` to an empty string. Before the whole validation thing kicks off I'm saving all relevant keys in an array, so by the time I need to sanitize or validate I've got something like this available: ``` $keys = array( 0 => 'should', 1 => 'be', 2 => 'int' ); ``` I've tried to then access the `$data` array using the above keys in a foreach loop by referencing the `&$data` array to set the new value, but haven't been able to, no matter what I tried. The above is just a simplified example. The whole thing is part of a validation class, so I don't know the exact depth of the passed `$data` array. Any pointers would be greatly appreciated! Thanks for your help! Edit: Thought I couldn't edit the post, but it ended up just being my internet connection. Please disregard my comment below. Anyways, here is a method that I tried calling recursively: ``` protected function set_value( &$data, $value ) { foreach( $data as &$val ) { if( is_array( $val ) ) { $this->set_value( $val, $value ); } else { $val = $value; } } } ``` To start the loop off I did this: ``` $this->set_value( $data[$keys[0]], $value ); ```