1

I have an array that contains string that have underscores or _ in them, I need to replace the underscores with spaces using str_replace and I want to do it using array_map()

array_map can take function that only have one parameter in them but str_replace takes three parameters:

  1. What to replace
  2. Replace it with what
  3. String

I can perfectly use a foreach loop to do the following but I was wondering how would I be able to do it with array_map. I did some looking on google and in stackoverflow but I couldn't find a solution.

Here's an example of the array that I have

$array = array("12_3","a_bc");
Ali
  • 3,479
  • 4
  • 16
  • 31
  • Well the title of that is not really clear to how it involves my problem, just the body. You can't expect me to find it with such a title really.. – Ali Jun 11 '13 at 09:02
  • If you search for 'array_map' you get plenty of examples imho! – tlenss Jun 11 '13 at 09:04
  • My bad. will search more generally next time. – Ali Jun 11 '13 at 09:06

3 Answers3

0

A simple solution to this problem would be to make a wrapper function that returns a string in the format you want using str_replace and then map that to the array.

Although if you read the documentation it says: "The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()"

The third argument is: "Variable list of array arguments to run through the callback function."

So you would want to do array_map("function", array_you_want_changed, array_of_paramters);

http://php.net/manual/en/function.array-map.php

See example 3.

AdamG
  • 3,718
  • 2
  • 18
  • 28
0

Here is how you can solve your problem.

$array = array("12_3","a_bc");

$find = array_fill(0, count($array), '_');
$replace = array_fill(0, count($array), ' ');


$out = array_map('str_replace', $find, $replace ,$array);

print_r($out);
DevZer0
  • 13,433
  • 7
  • 27
  • 51
0

You can try like this

<?php
function replace($array)
{
    $replace_res = str_replace('_', ' ', $array);
    return  $replace_res;
}

$array = array("12_3","a_bc");
$result = array_map("replace", $array);
print_r($result);
?>
Toretto
  • 4,721
  • 5
  • 27
  • 46