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".
is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .
Answer: Use the PHP array_filter() function You can simply use the PHP array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function.
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.
All elements of an array value must have the same data type. The cardinality of the array is equal to the number of elements in the array. An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With