Jump to content


Photo

Fastest way to set loads of variables to null?


  • Please log in to reply
3 replies to this topic

#1 Perad

Perad
  • Members
  • PipPipPip
  • Advanced Member
  • 287 posts

Posted 19 October 2006 - 02:43 PM

I have a form with a load of entry fields. I want to check to see if the field is empty, if the fields empty i want the variable to be set to null.

I have all these variables...
				$user_id = $userdata['user_id'];
				$f_name = $_POST['first_name'];
				$l_name = $_POST['last_name'];
				$gfx = $_POST['hw_gfx'];
				$mb = $_POST['hw_mb'];
				$pro = $_POST['hw_pro'];
				$mem = $_POST['hw_mem'];
				$mouse = $_POST['hw_mouse'];
				$fgame = $_POST['fav_game'];
				$ffilm = $_POST['fav_film'];
				$fbook = $_POST['fav_book'];
				$notes = $_POST['notes'];

Please tell me there is a better way than

if (empty($_POST['first_name'])) {
						$f_name = NULL;
					} else {
						$f_name = $_POST['first_name'];
					}


#2 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 19 October 2006 - 02:47 PM

try something like this:
<?php
foreach ($_POST as $key => $val) {
  if (empty($val)) $$key = NULL;
  else $$key = $val;
}
?>

You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#3 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 19 October 2006 - 02:51 PM

How about a function?

<?php
$user_id = set_to_null($userdata['user_id']);
$f_name = set_to_null($_POST['first_name']);
$l_name = set_to_null($_POST['last_name']);
$gfx = set_to_null($_POST['hw_gfx']);
$mb = set_to_null($_POST['hw_mb']);
$pro = set_to_null($_POST['hw_pro']);
$mem = set_to_null($_POST['hw_mem']);
$mouse = set_to_null($_POST['hw_mouse']);
$fgame = set_to_null($_POST['fav_game']);
$ffilm = set_to_null($_POST['fav_film']);
$fbook = set_to_null($_POST['fav_book']);
$notes = set_to_null($_POST['notes']);

function set_to_null($var){
   if (empty($var)){
      $var = NULL;
   }
   return $var;
}
?>

Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#4 printf

printf
  • Staff Alumni
  • Advanced Member
  • 889 posts

Posted 19 October 2006 - 02:55 PM

You could just use array_map(), if you changed your naming conversions so the conversion followed the same key_name pattern!

me!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users