0

I have an array called $whereClauses and I'm trying to convert any NULL values within the array to empty strings. I found this code below from a previous question on stackoverflow but I can't figure out how to apply it to my array. Any help would be much appreciated.

I have updated the code to show what I am doing.

foreach ($array as $key => $value) {
    if (is_null($value)) {
         $array[$key] = "";
    }
}

//Updated code

 if (isset($_POST['btn'])) {


    $whereClauses = array(); 
      if (! empty($_POST['location'])) $whereClauses[] ="(location ='".mysqli_real_escape_string($db_conx,$_POST['location'])."')"; 

    $whereClauses[] ="(activated='1')";


        //Convert Null values to empty strings
    foreach ($whereClauses as $key => $value) {
        if (is_null($value)) {
             $whereClauses[$key] = "";
        }

    }
    var_dump($whereClauses);

    }

Output:

array(2) { [0]=> string(18) "(location ='null')" [1]=> string(15) "(activated='1')" }
0

2 Answers 2

1

The code snipped seems to be the right direction, without having seen your code, I'd think it should work if you replace $array with the name of your array, i.e. sth like this:

foreach ($whereClauses as $key => $value) {
    if (is_null($value)) {
         $whereClauses[$key] = "";
    }
}

What issue are you running into? What does your array look like, can you post example values?

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

2 Comments

I've tried this out but I still get a null value. I have added more of the code to show what I am doing above.
In your array, the keys are index integers (0 and 1), and the values are the following strings: "(location ='null')" and "(activated='1')" So your array doesn't really have null values, since both keys are mapped to a string. I.e. your 'convert null value to empty string' code does not do anything. If you want to have an array that maps keywords ('location' and 'activated') to values ("" and 1), you need to add your array elements like this: $whereClauses['location'] = mysqli_real_escape_string($db_conx,$_POST['location']) $whereClauses['activated'] = 1
0

Replace $array with your array name:

foreach ($whereClauses as $key => $value) {
    if (is_null($value)) {
         $whereClauses[$key] = "";
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.