检查PHP数组中的空值,并使用默认值填充该特定键的值,如果为空[关闭]

检查PHP数组中的空值,并使用默认值填充该特定键的值,如果为空[关闭]

问题描述:

I have to read a PHP array for empty values. If there are any empty values for any key, I just wanted them to be filled with some default value if empty.

1. Is there any in built function to check if empty in an array and fill it up?

(OR)

2. What is the procedure to accomplish this requirement?

我必须读取PHP数组中的空值。 如果任何键都有空值,我只想让它们填充一些默认值,如果为空。 p>

1。 是否有内置函数来检查数组中是否为空并填满? strong> p>

(OR) p>

2。 完成此要求的程序是什么? strong> p> div>

array_map() can be used to apply a mapping to each array element.

$array = array(1, 0, 'foo', '', 'bar', NULL);
$default = 'DEFAULT';

var_dump(
  array_map(
    function($value) use ($default) {
      return $value ?: $default;
    },
    $array
  )
);

There isn't a built in function which replaces empty values.

You could loop through the array, and if the value is empty, populate it.

For example

foreach($arr as &$val) {
    if(empty($val)) { $val = 'Empty'; }
}

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

Try this,

$ar=array(" ","test"," ","test2");
$ar = array_replace($ar,
array_fill_keys(
    array_keys($ar, " "),
    "hi"
)
);