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

Here's a technique I haven't seen mentioned in the above answers:

$val = strval(@$arr["notfound"]);  // will not generate errors and
                                   // defaults to an empty string

This is super handy for $_GET parameter loading to keep things short and readable. Bonus, you can replace strval() with trim() ... or with intval() if you only accept integers.

The default for intval will be 0 if missing or a non-numeric value. The default for strval is "" if empty, null or false.

$val_str = strval(@$_GET['q']);
$val_int = intval(@$_GET['offset']);

See DEMO

Now for an array, you'll still need to loop over every value and set it. But it's very readable, IMO:

$arr = Array (1, 4, "0", "V", null, false, true, 'true', "N");

foreach ($arr as $key=>$value) {
  $arr[$key] = strval($value);
}

echo ("['".implode("','", $arr)."']");

Here is the result:

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

Interesting is that true becomes "1", but 'true' stays a string and that false becomes and empty string "".

Now the same data using $arr[$key] = intval($value); produces this result:

['1','4','0','0','0','0','1','0','0']
查看更多
Bombasti
3楼-- · 2020-02-10 15:31

This can be solved in one line using:

array_walk($array_json_return,function(&$item){$item=strval($item);});

here $array_json_return is the array.

查看更多
再贱就再见
4楼-- · 2020-02-10 15:32

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.

查看更多
登录 后发表回答