1

I want to replace all the null values in array with the blank values or empty string recursively.

Currrently my array is looking like this,which is perfect in structure, i want to replace every null value from it by empty string.

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [id] => 28
                    [name] => ABC
                    [goal] => 
                    [currency] => 
                    [images] => 
                    [start] => 1446159600
                    [stop] => 1446246000
                )
            [1] => Array
                 (
                    [id] => 29
                    [name] => XYZ
                    [goal] => 
                    [currency] => 
                    [images] => 
                    [start] => 1446159600
                    [stop] => 1446246000
                )
        )
)

Please show me shortest way to replace it.

3
  • 2
    Take a look at: array_walk_recursive() Commented Nov 21, 2015 at 11:40
  • Where do you see null values? I don't see any, because you are using the wrong debug print function. Try var_dump. Commented Nov 21, 2015 at 12:01
  • It is there, showing NULL values when i am using this array for JSON parsing. Commented Nov 25, 2015 at 12:41

2 Answers 2

8

As pointed out by Rizier123, you can do this with array_walk_recursive

function replaceNullValueWithEmptyString(&$value) {
    $value = $value === null ? "" : $value;
}

array_walk_recursive($array, "replaceNullValueWithEmptyString");
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the result array if you using the array_map(); function. Here is example code.

$item = array('a' => 'apple', 'b' => 'banana','c' => 'rama', 'd' => 'lingam','e' => '', 'f' => '');

function addNull($n)
{    
    if($n=='')
        return('NULL');
    else
        return($n);
}

$result_array = array_map("addNull", $item);

print_r($result_array);

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.