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

后端 未结 9 1614
一个人的身影
一个人的身影 2020-12-16 13:31

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] =>         


        
相关标签:
9条回答
  • 2020-12-16 13:45

    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.

    0 讨论(0)
  • 2020-12-16 13:48

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

    0 讨论(0)
  • 2020-12-16 13:48

    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);
    
    0 讨论(0)
  • 2020-12-16 13:49

    You can use this instead.

    array_map(function($val){return is_null($val)? "" : $val;},$result);
    
    0 讨论(0)
  • 2020-12-16 13:55

    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.

    0 讨论(0)
  • 2020-12-16 13:55
    foreach($array as $key=>$value)
    {
    if($value===NULL)
    {
    $array[$key]="";
    }
    }
    
    0 讨论(0)
提交回复
热议问题