How to convert the null values to empty string in

2020-02-10 14:42发布

I want to convert this array that Array[4] should not give null it can give blank space (empty string).

Array (
    [0] => 1
    [1] => 4
    [2] => 0
    [3] => V
    [4] => 
    [5] => N 
);

(The reason for the change, unrelated to the general question)

Fatal error: Uncaught exception
'PDOException' with message 'Database
error [23000]: Column 'message' cannot
be null, driver error code is 1048' in

标签: php arrays null
9条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-10 15:11

Use this function. This will replace null to empty string in nested array also

$arr = array(
          "key1"=>"value1",
          "key2"=>null,
          "key3"=>array(
                 "subkey1"=>null, 
                 "subkey2"=>"subvalue2"),
          "key4"=>null);

    echo json_encode(replace_null_with_empty_string($arr));

   function replace_null_with_empty_string($array)
    {
        foreach ($array as $key => $value) 
        {
            if(is_array($value))
                $array[$key] = replace_null_with_empty_string($value);
            else
            {
                if (is_null($value))
                    $array[$key] = "";
            }
        }
        return $array;
    }

Output will be :

{
  "key1": "value1",
  "key2": "",
  "key3": {
    "subkey1": "",
    "subkey2": "subvalue2"
  },
  "key4": ""
}

Try online here : https://3v4l.org/7uXTL

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-10 15:13

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 :)

查看更多
淡お忘
4楼-- · 2020-02-10 15:14
foreach($array as $key=>$value)
{
if($value===NULL)
{
$array[$key]="";
}
}
查看更多
何必那么认真
5楼-- · 2020-02-10 15:19

You can use this instead.

array_map(function($val){return is_null($val)? "" : $val;},$result);
查看更多
仙女界的扛把子
6楼-- · 2020-02-10 15:26

PHP 5.3+

    $array = array_map(function($v){
        return (is_null($v)) ? "" : $v;
    },$array);
查看更多
乱世女痞
7楼-- · 2020-02-10 15:26

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);
查看更多
登录 后发表回答