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

后端 未结 9 1613
一个人的身影
一个人的身影 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 14:09

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

提交回复
热议问题