Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace substring in column values of a 2d array

I'm trying to use str_replace() to remove the "my." out of the value4 elements in an array of arrays.

However, str_replace("my.", "", $myarray); isn't changing anything.

Does str_replace() not work on two-dimensional arrays?

My sample data and coding attempt:

$array = [
    [
        'value1' => 'John Doe',
        'value2' => 'Father',
        'value3' => '',
        'value4' => 'http://www.website.my.com'
    ],
    [
        'value1' => 'Jane Doe',
        'value2' => 'Mother',
        'value3' => '',
        'value4' => 'http://www.website.my.com'
    ]
    // ...
];
$out = str_replace('.my', '', $array);
var_export($out);
like image 633
n1nja Avatar asked May 14 '26 03:05

n1nja


1 Answers

No, it works on strings, or single dimension arrays.... you could use it through the callback in an array_walk_recursive though

array_walk_recursive(
    $myarray,
    function (&$value) {
        $value = str_replace('.my', '', $value);
    }
);
like image 65
Mark Baker Avatar answered May 16 '26 16:05

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!