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

Shaz
  • 15,637
  • 3
  • 41
  • 59
Lizard
  • 43,732
  • 39
  • 106
  • 167

4 Answers4

63

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

chiborg
  • 26,978
  • 14
  • 97
  • 115
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
)
binaryLV
  • 9,002
  • 2
  • 40
  • 42
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);
Community
  • 1
  • 1
salathe
  • 51,324
  • 12
  • 104
  • 132
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;
}
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94