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".

1
  • 1
    if this happens to be going in to a db, you can default a field to null Commented Oct 10, 2012 at 23:36

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

2

Now you can use arrow function also:

$array = array_map(fn($v) => $v === '' ? null : $v, $array);

Comments

0

You can use array_walk_recursive function.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.