15

I'm sorry but i researched a lot about this issue. Is there a standard function to search and replace array elements?

str_replace doesn't work in this case, because what i wanna search for is an empty string '' and i wanna replace them with NULL values

this is my array:

$array = (
    'first' => '',
    'second' => '',
);

and i want it to become:

$array = (
    'first' => NULL,
    'second' => NULL,
);

Of course i can create a function to do that, I wanna know if there is one standard function to do that, or at least a "single-line solution".

helpse
  • 1,518
  • 1
  • 18
  • 29
  • 1
    if this happens to be going in to a db, you can default a field to null –  Oct 10 '12 at 23:36

4 Answers4

34

I don't think there's such a function, so let's create a new one

$array = array(
   'first' => '',
   'second' => ''
);

$array2 = array_map(function($value) {
   return $value === "" ? NULL : $value;
}, $array); // array_map should walk through $array

// or recursive
function map($value) {
   if (is_array($value)) {
       return array_map("map", $value);
   } 
   return $value === "" ? NULL : $value;
};
$array3 = array_map("map", $array);
Martin.
  • 10,494
  • 3
  • 42
  • 68
13

As far as I know, there is no standard function for that, but you could do something like:

foreach ($array as $i => $value) {
    if ($value === "") $array[$i] = null;
}
rid
  • 61,078
  • 31
  • 152
  • 193
2

Now you can use arrow function also:

$array = array_map(fn($v) => $v === '' ? null : $v, $array);
Mladen Janjetovic
  • 13,844
  • 8
  • 72
  • 82
0

You can use array_walk_recursive function.

$array = [
 'first' => '',
 'second' => ''
];
array_walk_recursive($array, function(&$value) { $value = $value === "" ? NULL : $value; });