Home > Back-end >  search string inside key and values of a associative array php
search string inside key and values of a associative array php

Time:07-18

I have a array looks like this one blow =>

$aarray = [
  "table" => "Balance",
  "where" => ["Balance[ ]" => "NOMONEY[-]"]
     ];

how i can search through that for words like "[ ]" or "[-]" and replace them with something else ?
ps : wanna search and replace in both key and value of associative array
another ps : I cant find anything doing same as i wish in google or this forum

CodePudding user response:

Using your sample data, you could nest as deep as you want until PHP's recursion limit.

$array = [
    "table" => "Balance",
    "where" => ["Balance[ ]" => "NOMONEY[-]"],
];

$new = replaceInArray($array, "[-]", "(minus)");
$new = replaceInArray($new, "[ ]", "(plus)");
print_r($new);

Here is a simple recursive function to replace keys and values

function replaceInArray($array, $search, $replace, &$newArray = [])
{
    foreach ($array as $key => $value) {
        $key = str_replace($search, $replace, $key);
        if (is_array($value)) {
            $newArray[$key] = replaceInArray($value, $search, $replace);
        } else {
            $newArray[$key] = str_replace($search, $replace, $value);
        }
    }

    return $newArray;
}

will print out

Array
(
    [table] => Balance
    [where] => Array
        (
            [Balance(plus)] => NOMONEY(minus)
        )

)
  • Related