Transform any null input to empty string - php

So I've got a while loop, inside I have $array_collections that gives me 35 value per loop, I want to verify for every value if it's equal to NULL then give it an empty string. I did that :
while ($array_collections = tep_db_fetch_array($query)) {
foreach ($array_collections as $key => $value) {
if (is_null($value)) {
$array_collections[$key] = "";
}
}
$docs[] = new \Elastica\Document('', \Glam\HttpUtils::jsonEncode(
array(
'X' => $array_collections['X'],
... etc
)));
}
This technically should work, but the loop goes over 500K elements so it's huge, and for every element we put it into a table, problem is that I run out of memory at some point. So is there another simple way to give any given NULL value an empty string without looping?

well, you can put NOT NULL constraint with empty string as DEFAULT value in the DB for that so you dont need to do that in php using looping, but if you dont want to change the DB design then you can use COALESCE in your query
select COALESCE(yourfield,'') from table
it will convert NULL value into empty string

You can use array_map function to replace null values into empty string.
$array_collections=array_map(function($ar)
{
if(isset($ar) && $ar!=null){
return $ar;
}
return '';
},$array_collections);
Above code replace all null values to empty string. No need of loop.

you can use array_walk:
function replace_null(&$lsValue, $key) {
if(is_null($lsValue)) {
$lsValue = "";
}
}
array_walk($array_collections, 'replace_null');

Related

MySQL weird behavior with null integer

So I'm trying to implement php-etl to my application and MySQL doesnt let me insert null to nullable integer but it does if I manually change it, like this:
### This works ###
foreach($data as $row){
if($row["some_integer"] == Null){
$row["some_integer"] = Null;
}
if($row["some_other_integer"] == Null){
$row["some_other_integer"] = Null;
}
MyModel::create($row);
}
### This throws General error: 1366 Incorrect integer value ###
foreach($data as $row){
MyModel::create($row);
}
Tried both manually and with marquine/php-etl package. The input is csv file, null is empty space between ;; separators. Anybody knows what is going on here? Working on laravel 7.
Ok so the package loads the values as empty strings and by setting it Null it becomes real null... Is there a way to quicky convert these values to null?
MySQL won't treat an empty string as null, simply because an empty string and null are two different things. So the message you get from MySQL isn't weird, it's correct.
Nullify all empty strings in an array
If you just want to nullify all empty strings in an array, you can create a simple function for it:
function nullifyEmptyStrings(array $array)
{
return array_map(function ($item) {
return $item !== '' ? $item : null;
}, $array);
}
Then call it where ever/when ever you need it:
$row = nullifyEmptyStrings($row);
or use it directly in the argument for the create function:
MyModel::create(nullifyEmptyStrings($row));
Here's a demo
Nullify specific empty strings in an array
If you want to be able to define which array items to nullify, you can use this function:
function nullifyEmptyArrayValues(array $array, array $keys)
{
foreach ($keys as $key) {
if (array_key_exists($key, $array) && $array[$key] === '') {
$array[$key] = null;
}
}
return $array;
}
And in your code, you first pass the array containing the data and then another array with the keys to nullify, if the values are empty:
$row = nullifyEmptyArrayValues($row, ['some-key', 'another-key']);
Here's a demo

PHP verify array elements are all empty

I need to ensure that all the elements in my array are empty strings to process an action. The way I am currently doing it is incrementing a variable each time an element is an empty string. Then I check the value of that variable against a certain requirement N. If N is met, the action is processed. Below is the snippet of the code that checks for empty strings. I am not sure if this is the best way to do it and think there has to be a better way to do it because basically I am hard coding that value N. Can anybody else suggest another approach?
function checkErrorArray($ers) {
$err_count = 0;
foreach ($ers as &$value) {
if ($value == '') {
$err_count++;
}
}
return $err_count;
}
Why don't you do:
function areAllEmpty($ers) {
foreach ($ers as &$value) {
//if a value is not empty, we return false and no need to continue iterating thru the array
if (!empty($value)) return false;
}
//if got so far, then all must be empty
return true;
}
It will not have to run through the whole array if a non-empty value is found.
You could also do a shorter version:
function areAllEmpty($ers) {
$errs_str = implode('', $ers);//join all items into 1 string
return empty($errs_str);
}
Hope this helps.
Just filter it and if it is empty then ! will return true if not empty it will return false:
return !array_filter($ers);
Or if you actually need the count of empty elements then:
return count(array_diff($ers, array_filter($ers)));

Loop until null value is given

I've a third party library that returns values from a function and gives null if no value is present (not a database).
I've got the first value and I want to use it to return the second one and use the second one to return the third and so on. When a null value is returned, this loop should stop.
So the function uses an ID to get the next value eg: getNextValue($id). The return of this function is value or null.
So how should I include this function in a loop that uses a start value and returns the second, and uses the second to return the third and so on, until it returns a null value so it stops?
while ($value = getNextValue($id)) ...
while ($id = getNextValue($id)) {
//this will keep passing $id to the function over and over again
//Assuming your function will return different input or a null, this will work.
//code
}
while (null !== ($value = getNextValue($id))) {
}

Going through my entire $_SESSION array and removing null variables

I've been doing some tests with $_SESSION variables and that left a lot of them set to NULL, but still existing. I can remove them one-by-one, but how can I just loop through the $_SESSION array and remove NULL variables quickly?
You can use array_filter with a callback function that uses is_null:
$output = array_filter($input, function($val) { return !is_null($val); });
$_SESSION = array_filter($_SESSION, 'count');
Will have the effect of removing all NULL values (since count() returns 0 for NULL) and also any countable (either an array or an object) that has 0 elements, from the PHP manual:
Returns the number of elements in var,
which is typically an array, since
anything else will have one element.
If var is not an array or an object
with implemented Countable interface,
1 will be returned. There is one
exception, if var is NULL, 0 will be
returned.
Since 0 evaluates to false in a boolean context there is no need to implement any custom function.
This will remove NULL values, but not other empty or FALSE. Easily modified if you also want rid of FALSE vals and empty strings, etc.
foreach ($_SESSION as $key=>$var)
{
if ($var === NULL) unset($_SESSION[$key]);
}
$_SESSION = array_filter($_SESSION);
This will remove any "falsy" values from the session array, including null.
That should do it:
foreach ($_SESSION as $key => $value)
{
if ($value === NULL)
unset($_SESSION[$key];
}
P.S. array_filter will remove anything equal to "false". You should provide your own callback function or use this example if you need to remove only NULL-values and keep empty strings or zeros.
foreach($_SESSION as $key => $value){
if(empty($value) || is_null($value)){
unset($_SESSION[$key]);
}
}
If you are "deleting" $_SESSION elements by setting value to NULL, you are doing it wrong. To unset array element you should use
unset
on $_SESSION element.
# Wrong
$_SESSION['foo'] = NULL;
#Good
unset($_SESSION['foo']);

PHP array searching question

I have arrays, some are multidimensional as well. I need a way to know if all the values are NULL. What would be the most efficient and effective way of determining if ALL values of an array (as well as the values of the arrays within that array) are NULL?
So basically: search array, if all values are NULL, $flag = true
EDIT: The values are being pulled from a MySQL database where NULL is in the context of MySQL, if that makes a difference.
If i remember well db null fields become empty strings in php so you can use a function like this:
function isEmptyArray($array){
foreach($array as $val)
if((is_array($val) && !isEmptyArray($val))||(!is_array($val) && $val!="")) return false;
return true;
}
Depends on what would you use that flag for, but I think the best would be to query the database so it retrieves only non null values, like
select col1,col2,col3 from table where col1 is not null and col2 is not null
and col3 is not null
That said, a simple way to do something like that in PHP would be
//array_filter filters values that evaulate to fals
$result = array_filter($input);
if (count($result) == 0) { $flag = true; }
This will fail for multidimensional arrays and if zeroes or other values that get automatically converted to false are valid values in your array, if this is the case you have to build a recursive callback function and pass it as a second parameter to array_filter.
You may want to look at the array_filter() function, by default it strips out values that equate to false (this includes NULL).
I'm not sure if it'll work as is for mutli-dimensional arrays, but it has the option to use call back functions which would easily allow you to handle that.
Long story short, if you run array_filter on the array and you get an empty array returned then all your values are Null or equal to false - if you need to differentiate between these values in a strict sense, then you should use a call back.
Can be done recursively:
arrayIsFullyNull ($arr)
{
if (is_array($arr))
foreach ($arr as $val)
if (!arrayIsFullyNull($val))
return false;
else if (!is_null($arr))
return false;
else
return false; // it's not null, and not array => value
return true;
}
You could use a RecursiveArrayIterator to walk over all the values (leaves of the tree of of nested arrays).
Untested code:
function isNullOrNestedArrayOfNulls($array)
{
if (is_null($array)
{
return true;
}
else if (!is_array($array))
{
return false;
}
$allNull = true;
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($array),
RecursiveIteratorIterator::LEAVES_ONLY);
while ($iter->valid())
{
if (!is_null($iter->current())
{
$allNull = false;
break;
}
}
return $allNull;
}
This would have the advantage of avoiding a recursive function (which have the reputation of being rather inefficient in PHP).

Categories