0

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'    
]
1
  • Can you just put your array format from which you want to remove something . Not whole but somehow, it help us to give you some solution because we don't know what is your array formt? Commented Mar 20, 2015 at 7:23

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I think you need to return $ary, right? But this is definitely helpful.
@Kevin: $ary is passed by reference and modified in place. No need to return it.
Thanks! I missed that.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.