php - How can I replace a string inside a multidimensional array?


How can I replace a string/word that's inside a multidimensional array with a new value? I don't have its key, just know the haystack and the needle.

Say I have a multidimensional array,$submenu_arr, (don't know how many dimensions).

I want to find a value inside one of these arrays and replace it with a new value.

Actually for a translation.


 recursive_arr_translation('Article', $submenu_arr, 'Artigo');//"Artigo" is a Portuguese word for "Article".

I've tried this, but not working:

 function in_array_r($needle, $haystack, $new_value) {
        $found = false;
        foreach ($haystack as $key=>$value) {
        if ($value === $needle) { 
                $found = true; 
                $haystack[$key] = $new_value;
                return true;
            } elseif (is_array($value)) {
                $found = in_array_r($needle, $haystack[$key], $new_value); 
                if($found) { 
                    return true; 
        return $found;

in_array_r('Article', $submenu, 'Artigo');
in_array_r('Location', $submenu, 'Localização');

EDIT: Is working, but somehow, I don't get it working, I'm trying to translate a WordPress submenu word.




You can use as suggested in the comments, and pass your original array as reference, allowing us to edit it.


$a = array("Giraffe", "Monkey", "Elephant", "Snake", 5, "other" => array("apple", "orange"));

array_walk_recursive($a, function(&$a) {
        if($a == "apple") {
             $a = "Banana";

echo print_r($a, true);

So, now we have the basic logic, let's create a function with 3 parameters.

function replace_in_array($find, $replace, &$array) {
    array_walk_recursive($array, function(&$array) use($find, $replace) {
        if($array == $find) {
             $array= $replace;
    return $array;

$a = array("Giraffe", "Monkey", "Elephant", "Snake", 5, "other" => array("apple", "orange"));
echo print_r( replace_in_array("apple", "banana", $a), true);

People are also looking for solutions to the problem: php - Are apc_store and apc_fetch functions suitable for intensive use? (scenario described)


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.