Replacing empty string with nulls in array php

2019-01-25 09:24发布

问题:

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:

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


回答2:

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