0

I save the form elements to a file and the following is working as expected.

$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n";

But what I need is that if $_GET is set only then it should be appended to "t_str" string.

If no value for viewMandatory is received from the form, it should print nothing. How to add this check to the above statement?

shantanuo
  • 30,102
  • 75
  • 225
  • 364
  • There are [a lot](http://stackoverflow.com/questions/3496971/check-if-post-exists) of [similar](http://stackoverflow.com/questions/3432282/check-if-any-variables-are-passed-in-a-get) questions, and a [Google search is quite fruitful](http://www.google.co.uk/webhp?#hl=en&output=search&sclient=psy-.ab&q=check+if+get+variable+exists&fp=1). – Alex Apr 09 '12 at 07:16

3 Answers3

5
if (!empty($_GET['viewMandatory'])){
$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n";
}

After 292 questions you should have encountered the empty() function.

Sinister Beard
  • 3,535
  • 11
  • 55
  • 92
1
$t_str .= (!empty($_GET['viewMandatory'])?$_GET['viewMandatory']:null;

This way you have less code, what makes it easier to read (at least to me, i love short forms), but the code will be executed everytime you request the page. that is not the case with Dragon's solution.

But think about code injection. Filter $_GET['viewMandatory'] the correctway before adding it to your string! Otherwise bad code can be injected quite easy, e.g.:

www.yourpage.com/page.php?viewMandatory=';BAD_CODE_HERE (or " instead of ')
Mohammer
  • 393
  • 2
  • 15
1
Use php isset    


if (isset($_GET['viewMandatory'])){
$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n";
}
Muhammad Raheel
  • 19,645
  • 7
  • 66
  • 101