This is my recursive function, which can change not only the values ββof an array like array_walk_recursive () , but also the keys of this array. It also preserves the order of the array.
function modifyArrayRecursive(array &$_array, callable $_callback): void { $keys = \array_keys($_array); foreach ($keys as $keyIndex => $key) { $value = &$_array[$key]; if (\is_array($value)) { modifyArrayRecursive($value, $_callback); continue; } $newKey = $key; $newValue = $value; $newPair = $_callback ($key, $value); if ($newPair !== null) { [$newKey, $newValue] = $newPair; } $keys[$keyIndex] = $newKey; $_array[$key] = $newValue; } $_array = \array_combine($keys, $_array); } modifyArrayRecursive($keyboardArr, function ($key, $value) { if ($value === 'some value') { return ['new_key_for_this_value', $value]; } return null; });
source share