My goal is to remove a group of characters from a one dimensional array's keys and another group of characters from that same array's values. Example:
$arr = [
'a' => 'Letter A!',
'`b`' => 'Letter B w/quotes...',
' c ' => 'Letter C w/spaces?',
' -_-`d`- _ - ' => 'Letter D w/all?!...'
];
$invalid_keys_chars = ['`',' ','_','-'];
$invalid_vals_chars = ['!','?','.'];
// GOAL: looking for something like this function
array_del_invalid($arr, $invalid_keys_chars, $invalid_vals_chars));
var_export($arr);
// ---> output
// array (
// 'a' => 'Letter A',
// 'b' => 'Letter B w/quotes',
// 'c' => 'Letter C w/spaces',
// 'd' => 'Letter D w/all'
// )
I looked first into common PHP functions:
array_walk
example: allows the replacement of values by reference, but if I also pass the key by reference in the callback parameters the same doesn't happen;array_replace
: keys are also not modified;array_map
example: constructing a copy of an array, but previous treatment ofarray_keys($arr)
is necessary.
So my goal is to perform all the replacements in one go, avoiding reusing PHP functions that loop several times the array.
I placed an answer on this same thread with my attempt, which is working, but I couldn't figure out a way to avoid unset($arr[$invalid_key])
(is there another way to "change" the key itself without removing it?) or doing only one assignment if both key and value strings need replacement.
Is there already a PHP function that does this? I.e. single-loop, few conditions, minimum replacements and overall more efficient? If not, how can I improve mine?