Page 1 of 1

Make variable NULL if form field is empty

Posted: Wed May 18, 2005 7:47 am
by primate
I have a form with several optional fields that allows users to edit the content of a webpage.

When they come to edit the webpage I populate the form with the existing data in the database so its easy for them to amend what is already there. However if they delete an entire field, when the form is submitted the variable associated with the field is still set - var_dump() shows it as

Code: Select all

string(1) &quote; &quote;
. I'd like to set the variable to NULL if the variable is actually empty.

This is a problem because in order to format what is being shown on the resulting webpage I need to check if variables are NULL or empty somehow to either include or not inlcude sections of the page. At the moment since all the variables effectively have a value I am getting bits of the page I don't want to display.

So, can anyone make a suggestion how to get the variable unset if there's no real text in it?

Posted: Wed May 18, 2005 8:06 am
by hongco
if(empty($Var))
$Var= NULL;

Posted: Wed May 18, 2005 8:21 am
by primate
Thanks, but I've already tried that, its not empty because its " " rather than "" I think.

Posted: Wed May 18, 2005 1:15 pm
by Sphen001
Well, if you know the variable will be

Code: Select all

" "
why not check for that.

Code: Select all

if ($var == " ")
{
  $var = NULL;
}
Hope this helps :D

Sphen001

Posted: Fri May 20, 2005 3:23 am
by primate
Yeah :) thats what I decided to do, but I was trying to find out why that was the case, rather than just work around it if you see what I mean.

Posted: Fri May 20, 2005 6:05 am
by wwwapu
But what if variable is

Code: Select all

"  "
instead of

Code: Select all

" "
Don't know if this works but...

Code: Select all

if(empty(trim($Var))) 
$Var= NULL;