You can easily change using the function array_walk
together with a good regular expression.
array_walk - Apply a user supplied Function to Every Member of an array
As the manual says, array_walk
traverse all elements of an array by applying to each of them a function given as parameter.
To remove the parentheses, I will use a regular expression. A ER
in question, it is simple \(([^()]+)\)
. Translating, it means "anything within parentheses other than parentheses".
As already informed, it is necessary to provide a function to array_walk
. In this case, a function such as callback
. The function is as follows:
$callback = function(&$value , $key) {
preg_match('/\(([^()]+)\)/' , $value , $matches);
$value = $matches[1];
};
Applying your array with the callback
.
array_walk($array , $callback);
You will get the following result:
array(3) { ["chave1"]=> string(6) "valor1" ["chave2"]=> string(6) "valor2" ["chave3"]=> string(6) "valor3" }
A doubt, in performance, the
array_map
overcomes a repeat structure? + 1, great solution.– Leonardo
@lvcs did not take any performance test, which I can say that
array_map()
/array_walk()
can be more practical in some situations, avoiding thefor
/foreach
.– rray
@Ivcs All native functions (written in C) are superior in performance than any structure created with pure PHP.
– Gabriel Heming
@rray yes for sure is more practical :)
– Leonardo
Worked like a charm!
– DiChrist
a hint will be you always opt for PHP’s own methods, as in the case of array_map(), because they are optimized to work in the best way with the language.
– Leandro Macedo