Perad Posted October 19, 2006 Share Posted October 19, 2006 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] Quote Link to comment https://forums.phpfreaks.com/topic/24448-fastest-way-to-set-loads-of-variables-to-null/ Share on other sites More sharing options...
obsidian Posted October 19, 2006 Share Posted October 19, 2006 try something like this:[code]<?phpforeach ($_POST as $key => $val) { if (empty($val)) $$key = NULL; else $$key = $val;}?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/24448-fastest-way-to-set-loads-of-variables-to-null/#findComment-111311 Share on other sites More sharing options...
HuggieBear Posted October 19, 2006 Share Posted October 19, 2006 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] Quote Link to comment https://forums.phpfreaks.com/topic/24448-fastest-way-to-set-loads-of-variables-to-null/#findComment-111314 Share on other sites More sharing options...
printf Posted October 19, 2006 Share Posted October 19, 2006 You could just use array_map(), if you changed your naming conversions so the conversion followed the same key_name pattern!me! Quote Link to comment https://forums.phpfreaks.com/topic/24448-fastest-way-to-set-loads-of-variables-to-null/#findComment-111319 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.