Question

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");
Was it helpful?

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top