Search code examples
phparraysstr-replacearray-map

How to use array_map with a function that takes more than one parameter?


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

Solution

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