Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing empty string with nulls in array php

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

like image 283
helpse Avatar asked Oct 10 '12 23:10

helpse


People also ask

Is NULL equal to empty string PHP?

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 .

How do you remove an empty value from an array?

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.

How do you declare a NULL array in PHP?

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.

Can arrays hold nulls?

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.


1 Answers

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);
like image 144
Martin. Avatar answered Sep 25 '22 07:09

Martin.