Is it possible to use array_map
in conjunction with str_replace
without calling another function to do the str_replace
?
For example:
array_map(str_replace(' ', '-', XXXXX), $myArr);
Is it possible to use array_map
in conjunction with str_replace
without calling another function to do the str_replace
?
For example:
array_map(str_replace(' ', '-', XXXXX), $myArr);
There is no need for array_map. From the docs: "If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well."
No, it's not possible. Though, if you are using PHP 5.3, you can do something like this:
$data = array('foo bar baz');
$data = array_map(function($value) { return str_replace('bar', 'xxx', $value); }, $data);
print_r($data);
Output:
Array
(
[0] => foo xxx baz
)
Sure it's possible, you just have to give array_map()
the correct input for the callback function.
array_map(
'str_replace', // callback function (str_replace)
array_fill(0, $num, ' '), // first argument ($search)
array_fill(0, $num, '-'), // second argument ($replace)
$myArr // third argument ($subject)
);
But for the particular example in the question, as chiborg said, there is no need. str_replace()
will happily work on an array of strings.
str_replace(' ', '-', $myArr);
Might be important to note that if the array being used in str_replace
is multi-dimensional, str_replace
won't work.
Though this doesn't directly answer the question of using array_map
w/out calling an extra function, this function may still be useful in place of str_replace
in array_map
's first parameter if deciding that you need to use array_map
and string replacement on multi-dimensional arrays. It behaves the same as using str_replace
:
function md_str_replace($find, $replace, $array) {
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
$newArray = array();
foreach ($array as $key => $value) {
$newArray[$key] = md_str_replace($find, $replace, $value);
}
return $newArray;
}
© 2022 - 2024 — McMap. All rights reserved.
str_replace()
to an array, or map the result of replacing something as a function name, to the array? – Kibler