Omzy Posted December 15, 2009 Share Posted December 15, 2009 I find myself doing this a lot of the time: if(isset($_POST['name'])) $name=$_POST['name']; I get the feeling there is a simpler way of doing this. It's not such a bother if it's just one or two but its when you have a whole bunch of these that it gets tedious! Quote Link to comment Share on other sites More sharing options...
mikesta707 Posted December 15, 2009 Share Posted December 15, 2009 you can use the ternary operator $name = (isset($_POST['name'])) ? $_POST['name'] : null; but thats not much better. Assuming you want to always check if the post variable is set before you assign it to a variable, i don't see a better way than an if statement Quote Link to comment Share on other sites More sharing options...
phpfan101 Posted December 15, 2009 Share Posted December 15, 2009 forms name is "add" if (isset($_POST['add'])){ $var = $_POST['value']; $var2 = $_POST['value2']; $var3 = $_POST['value3']; } Quote Link to comment Share on other sites More sharing options...
phpfan101 Posted December 15, 2009 Share Posted December 15, 2009 well, that script doesn't add them, but just showing you the simplicity Quote Link to comment Share on other sites More sharing options...
premiso Posted December 15, 2009 Share Posted December 15, 2009 One alternative, have an array of form element names then loop through that assigning the data. $validElements = array("name", "email", "user", "password"); foreach ($validElements as $val) { $$val = isset($_POST[$val]) ? $_POST[$val] : null; } Which way is better is up to you to decide. Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 15, 2009 Share Posted December 15, 2009 You could create a function <?php function setValue (&$variable, $default) { return (isset($variable)) ? $variable : $default; } //Set values for testing only $foo['bar1'] = 'Passed Value'; //$foo['bar2'] = 'Passed Value'; //This value not set $bar1 = setValue($foo['bar1'], 'Value not set'); $bar2 = setValue($foo['bar2'], 'Value not set'); echo "bar1 = $bar1"; //Output: bar1 = Passed Value echo "bar2 = $bar2"; //Output: bar2 = Value not set ?> Quote Link to comment 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.