0

I am trying to make a condition in php for this situation:

You can choose for a radio input or checkbox input. No matter what you choose, but if you choose one of them, it may not be empty.

$quickpolltype = "radio"; // set to "radio" or "checkbox"; radio is one choice, checkbox is multiple choices

I have seperated the 2 conditions now like below:

if($quickpolltype == "radio" and $_POST['radiovote'] != '') {
// do something
}
if($quickpolltype == "checkbox" and $_POST['checkboxvote'] != '') {
// do something
}

what i want to achieve:

No matter what you choose as type in $quickpolltype, if the value of one of them is not empty --> do something

So how can i combine those 2 conditions in 1 condition, whatever quickpolltype is choosen?

Jack Maessen
  • 1,780
  • 4
  • 19
  • 51
  • if the value doesn't matter, then don't test it? `if(radiovote != '' && checkboxvote != '')` – Marc B Aug 05 '16 at 19:55

3 Answers3

4

First it is advisable to use && and || see here 'AND' vs '&&' as operator

Also you are doing an assignment = and not a comparison ==.

So you want something like:

if($quickpolltype == "radio" && $_POST['radiovote'] != '') {
    // do something
}
if($quickpolltype == "checkbox" && $_POST['checkboxvote'] != '') {
    // do something
}

Essentially you were making $quickpolltype "radio" rather then checking if it was equal to it. Same for "checkbox".

To make all of that in one if

if(($quickpolltype == "radio" && $_POST['radiovote'] != '') 
    || ($quickpolltype == "checkbox" && $_POST['checkboxvote'] != '')){
    //Do stuff
}
Community
  • 1
  • 1
nerdlyist
  • 2,842
  • 2
  • 20
  • 32
3

If the "do something" is going to be the same, you can certainly combine the two conditions. If not, keep them separate.

if(($quickpolltype=="radio" && $_POST['radiovote'] != '') || ($quickpolltype="checkbox" && $_POST['checkboxvote'] != '')) {
    //do something
}

Make sure that when comparing things in PHP, you are using "=="! Additionally, you may want to be careful of using "and" and "or" instead of "&&" and "||" in PHP.

Community
  • 1
  • 1
Linus Rastegar
  • 263
  • 3
  • 16
0

Radio buttons and Checkboxes are tricky beasts because if you select nothing then their name="radiovote" will never make it to be available in $_POST['radiovote'] so you need the power of isset(). Also make sure to use the appropriate && or || operators

if(
    in_array($quickpolltype, array("radio","checkbox")) &&
    (
        (isset($_POST['radiovote']) && $_POST['radiovote'] != '') ||
        (isset($_POST['checkboxvote']) && $_POST['checkboxvote'] != '')
    )
  )
{
    // Do something
}
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • This is semantically different from what the question asked for. It will `Do something` when `$quickpolltype == "radio"` even if `$_POST['radiovote'] == ''`, as long as `$_POST['checkboxvote'] != ''`. – Julian Aug 05 '16 at 22:28