array_map with str_replace
Asked Answered
A

4

26

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);

Astral answered 3/6, 2011 at 11:34 Comment(3)
What are you trying to do? Map str_replace() to an array, or map the result of replacing something as a function name, to the array?Kibler
Why don't you just try it? :)Broker
each element of the array to have str_replaceAstral
S
65

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."

Shick answered 3/6, 2011 at 11:47 Comment(0)
B
14

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
)
Batholomew answered 3/6, 2011 at 11:38 Comment(1)
@mkilmanas, what did you mean? And what was the reason for downvoting (if it was you)?Batholomew
G
9

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);
Gaff answered 3/6, 2011 at 11:59 Comment(0)
D
1

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;
}
Deep answered 19/9, 2012 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.