Kevin
Kevin

Reputation: 1569

How do I replace all occurances of a value in a multidimensional php array?

How would I replace any occurrence of value "FOO" with "BAR" in a nested/multidimensional php array? In my case, I'm trying to replace NAN (not a number) values with a string "NAN", but the same principles should apply. My incomplete example code:

function replaceNan($data)
{
    // probably some recursion here?
}

$data = [
    'foo' => NAN,
    'bar' => [
        'one' => 1,
        'nan' => NAN
    ],
    'baz' => 'BAZ'    
];

$data = replaceNan($data);
var_dump($data);

Unless there's a core php function that will help, I assume recursion will be involved, but I just can't figure it out right now. Any help appreciated.

Edit: Just to be clear, in my example, I would want $data to be modified so it looks like:

[
    'foo' => "NAN",
    'bar' => [
        'one' => 1,
        'nan' => "NAN"
    ],
    'baz' => 'BAZ'    
]

Upvotes: 0

Views: 245

Answers (2)

georg
georg

Reputation: 214959

How about

function replace_nan(&$ary) {
    foreach($ary as &$item) {
        if(is_double($item) && is_nan($item))
            $item = "NAN";
        else if(is_array($item))
            replace_nan($item);
    }
}

Array is passed by reference and modified in place:

$data = [...];
replace_nan($data);
var_dump($data);

Upvotes: 1

n-dru
n-dru

Reputation: 9430

This works for me:

 function replace_nan($a){
    foreach($a as $key1 => $array1){
         if(!is_array($array1)){
            if(!is_string($array1) && is_nan($array1)){
                $a[$key1] = "NAN";
            }
        }else{
            $a[$key1] = replace_nan($array1);
        }
    }
    return $a;
}

var_dump(replace_nan($data));

Yields:

array (size=3)
  'foo' => string 'NAN' (length=3)
  'bar' => 
    array (size=2)
      'one' => int 1
      'nan' => string 'NAN' (length=3)
  'baz' => string 'BAZ' (length=3)

Upvotes: 0

Related Questions