How to convert the null values to empty string in php array?

There is even better/shorter/simpler solution. Compilation of already given answers. For initial data

[1, 4, "0", "V", null, false, true, 'true', "N"]

with

$result = array_map('strval', $arr);

$result will be

['1', '4', '0', 'V', '', '', '1', 'true', 'N']

This should work even in php4 :)


This will map the array to a new array that utilizes the null ternary operator to either include an original value of the array, or an empty string if that value is null.

$array = array_map(function($v){
    return $v ?: '';
},$array);

PHP 5.3+

$array = array_map(function($v){
    return (is_null($v)) ? "" : $v;
},$array);

Then you should just loop through array elements, check each value for null and replace it with empty string. Something like that:

foreach ($array as $key => $value) {
    if (is_null($value)) {
         $array[$key] = "";
    }
}

Also, you can implement checking function and use array_map() function.

Tags:

Php

Arrays

Null