Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
PHP
if(isset($_POST['submit']))
{
  if(!empty($_POST['value1'] && $_POST['value2'] && $_POST['value3']))
  {
     //do something
  }
  elseif(!empty($_POST['value1'] && $_POST['value2']))
  {
     //do something (value 3 must not be posted***!)
  }
  elseif(!empty($_POST['value1']))
  {
     // do something (value 2 and 3 must not be posted***!)  
  }
}

Hi , my code above ... its probably wrong and the fact that it can pick the 3 if statements while I need it to pick only one of the 3 and can I write it any simpler ? Im posting a checkboxes value Using POST metod ... thanks!
Posted
Updated 17-May-15 8:07am
v3

1 solution

Yes, it can be written in a bit more elegant way - provided that there's no use for the case that value1 and value3 are set but not value2:
PHP
if(isset($_POST['submit']))
{
  if(!empty($_POST['value1']))
  {
    if($_POST['value2'])
    {
      if($_POST['value3'])
      {
        // do something that requires all values
      }
      else
      {
        // do something that requires only value1 and value2
      }
    }
    else
    {
      // do something that requires only value1
    }
  }
}

If you (here or somewhere else) need to check some $_POST[..]-value in multiple if-statements I would recommend that you assign it to some variable to use that from that point on, which will make it a bit more easy to read. Example here for the case that it would actually make sense to check what I excluded above (value1 and value3 but not value2):
PHP
if(isset($_POST['submit']))
{
  $value1empty = empty($_POST['value1']);
  $value2empty = empty($_POST['value2']);
  $value3empty = empty($_POST['value3']);

  $value1only = !$value1empty &&  $value2empty &&  $value3empty;
  $value1and2 = !$value1empty && !$value2empty &&  $value3empty;
  $value1and3 = !$value1empty &&  $value2empty && !$value3empty;
  $allValues  = !$value1empty && !$value2empty && !$value3empty;

  if($value1only)
  {
  }
  elseif($value1and2)
  {
  }
  // ...
}
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 17-May-15 14:56pm    
Simple enough, clearer, my 5.
—SA
Sascha Lefèvre 17-May-15 15:03pm    
Thank you, Sergey.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900