1

If I want to save a few $_POST variables so I can validate them or wtvr, I'd generally write something like:

$name = isset($_POST['name'])? $_POST['name'] : NULL;

But I want to do the exact same thing over and over again, a number of times. Is it bad practice to use @ in this case? $name = @$_POST['name'];

Or is there a better way to do this - like writing a function:

function getPostValue(field){
  return isset($_POST[field])? $_POST[field] : NULL;
}

and then $name= getPostValue('name'); ?

Thanks in advance!

ForOhFor
  • 686
  • 8
  • 15
  • 1
    @Gordon I searched a bunch, but didnt find that. Thanks! – ForOhFor Jul 30 '13 at 13:43
  • 1
    While the main question is a duplicate, a note about using `@` It's generally bad practice to suppress warnings in *any* case. – Jason McCreary Jul 30 '13 at 13:44
  • @JasonMcCreary thanks for addressing that. Why, though? – ForOhFor Jul 30 '13 at 13:45
  • Because most of the time anything that throws a Notice and/or Warning is bad practice. In this case you are trying to reference a value in an array that doesn't exist. – Pitchinnate Jul 30 '13 at 13:48
  • http://stackoverflow.com/a/960288/164998 – Jason McCreary Jul 30 '13 at 13:48
  • I've always wanted to experiment with `$posted = array_values($_POST)`. I think this would perform the same task over the entire array?? – DevlshOne Jul 30 '13 at 13:49
  • @DevlshOne that wouldn't tell you if a value is set and it also removes the keys, so you will lose any information about what the values represent. In other words, you wouldn't know and you wouldn't be able to check whether "name" is in that array. It would make more sense to use array_replace to overwrite the values in an array holding default values for the keys you want to operate on, e.g. something like http://pastebin.com/CQT3vy9N – Gordon Jul 30 '13 at 14:28

1 Answers1

2

You can customize your function like this :

function getPostValue($field, $default = null){
  return isset($_POST[$field])? $_POST[$field] : $default;
}

If you want to fetch integer type variable then you can use

echo getPostValue('id',0);
som
  • 4,614
  • 2
  • 18
  • 36