Make variable NULL if form field is empty

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Make variable NULL if form field is empty

Post 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?
hongco
Forum Contributor
Posts: 186
Joined: Sun Feb 20, 2005 2:49 pm

Post by hongco »

if(empty($Var))
$Var= NULL;
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Post by primate »

Thanks, but I've already tried that, its not empty because its " " rather than "" I think.
Sphen001
Forum Contributor
Posts: 107
Joined: Thu Mar 10, 2005 12:24 pm
Location: Land of the Beaver

Post 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
primate
Forum Commoner
Posts: 49
Joined: Fri Jun 18, 2004 4:38 am
Location: England, UK

Post 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.
User avatar
wwwapu
Forum Contributor
Posts: 197
Joined: Wed Apr 07, 2004 11:57 am
Location: Turku, Finland

Post 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;
Post Reply