Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a PHP array for empty values and fill that particular key's value with default value if empty [closed]

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?

like image 476
Neocortex Avatar asked Oct 16 '25 17:10

Neocortex


2 Answers

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
  )
);
like image 198
ThW Avatar answered Oct 18 '25 07:10

ThW


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'; }
}
like image 30
Ryan Avatar answered Oct 18 '25 07:10

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!