0

I have a page with many fields a user can fill out. The fields are not mandatory but I do not want to sent a empty value to mysql as that will create problems later on. I'm trying to create a loop that checks if a variable is empty, and if empty assign some static value. Because I got rather a lot of field vars I want to do this without having to specify each field var.

<?php
$arr = get_defined_vars();
foreach ($arr as $key => $value) {
    if (empty($value))
        echo "$key empty <br/>";

    else
        echo "$key not empty <br/>";
}

print_r($arr);
?>

Shows all fieldname:empty or fieldname:not empty.

I tried adding various things such as $arr[$key] = "TEST"; or $key = "TEST"; below if (empty($value)) but I cannot get the empty fields to update in the printed array.

sjaak
  • 644
  • 1
  • 7
  • 18
  • Rather than using `get_defined_vars()`, it may be better to create an array with a list of all of the variables you want to check to ensure have some sort of value. At the moment you may affect values used elsewhere in the code. – Nigel Ren Jun 09 '20 at 06:12
  • You can also set default values for fields in MySQL itself. That might be smarter than trying to do this from your code. – Ben Hillier Jun 09 '20 at 06:36
  • Unfortunatly that won't work I think because my fields will just push an empty value into mysql. mysql for whatever reason won't allow default values on text fields either. – sjaak Jun 09 '20 at 06:43

0 Answers0