phpstr-replacearray-maparray-replace

replace all values in array that have "o" letter in php


This is my array

$arr = array("dog", "cat", "lion");

Now i wanna replace any value that has the letter o with 0. Example :

$arr = array("d0g", "cat", "li0n");

This is my method for doing this :

$arr = array("dog", "cat", "lion");

$arr2 = array("d0g", "cat", "li0n");
$rep = array_replace($arr, $arr2);
var_dump($rep);

This method is completely manual. While I want a way to automatically track the letter 'o' in any value and move them with '0'.


Solution

  • You can use array_map (to map all values of an array to new ones using some transformation function) together with str_replace (to replace o by 0):

    $arr = ['dog', 'cat', 'lion'];
    
    $rep = array_map(fn($el) => str_replace('o', '0', $el), $arr);
    

    (Note that this uses PHP 7.4 arrow function syntax. You can use function ($el) { return str_replace('o', '0', $el) } instead of fn($el) => str_replace('o', '0', $el) if you have to use an older PHP version.)