0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! But what is less hungry, to do this, or use array_map ? But I didn't know about COALESCE(), I learnt something today.
0

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.

2 Comments

So many replies that answers my problem differently, thanks !
This answer is misleading and potentially wrong. The loose comparison on null will also be satisfied by any "falsey" value (like 0, '0', an empty string, and more). isset() already checks that a variable exists and is not null.
0

you can use array_walk:

function replace_null(&$lsValue, $key) {
     if(is_null($lsValue)) {
         $lsValue = "";
     }
}

array_walk($array_collections, 'replace_null');

Comments

Your Answer

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