Jump to content

Archived

This topic is now archived and is closed to further replies.

Perad

Fastest way to set loads of variables to null?

Recommended Posts

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...
[code]
$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'];[/code]

Please tell me there is a better way than

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

Share this post


Link to post
Share on other sites
try something like this:
[code]
<?php
foreach ($_POST as $key => $val) {
  if (empty($val)) $$key = NULL;
  else $$key = $val;
}
?>
[/code]

Share this post


Link to post
Share on other sites
How about a function?

[code]<?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;
}
?>[/code]

Share this post


Link to post
Share on other sites
You could just use array_map(), if you changed your naming conversions so the conversion followed the same key_name pattern!

me!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.