Andy
Andy

Reputation: 3021

Checking a value exists

I have the following checkboxes in my form, id like to know how to check at least one of them are checked without changing the name of them.

<label for="branding">Branding
<input type="checkbox" name="branding" id="branding" class="checkbox" /></label>
<label for="print">Print
<input type="checkbox" name="print" id="print" class="checkbox" /></label>
<label for="website">Website
<input type="checkbox" name="website" id="website" class="checkbox" /></label>
<label for="other">Other
<input type="checkbox" name="other" id="other" /></label>

Upvotes: 0

Views: 121

Answers (2)

Yacoby
Yacoby

Reputation: 55435

Use isset() or array_key_exists(). The two functions do have a very slight difference in that if the value is null, even if the key exists, isset returns false. However, it shouldn't matter in this case

if ( isset($_POST['branding']) || isset($_POST['print']) ){
    //...
}

Or possibly better

$ops = array('branding', 'print');
$hasSomethingSet = false;
foreach ( $ops as $val ){
     if ( isset($_POST[$val]) ){
         $hasSomethingSet = true;
         break;
     }
}

if ( $hasSomethingSet ){
    //...
}



If you have PHP 5.3, a slightly slower but more elegant solution is (untested):

$ops = array('branding', 'print');
$hasSomethingSet = array_reduce($ops, 
                                function($x, $y){ return $x || isset($_POST[$y]; },
                                false);

It depends on how happy with functional programming you are as to if you prefer it.

Upvotes: 5

Emyr
Emyr

Reputation: 2371

$checkcount = 0;
if($_POST['branding']){$checkcount++}
if($_POST['print']){$checkcount++}
if($_POST['website']){$checkcount++}
if($_POST['other']){$checkcount++}

if($checkcount>0){
    //do stuff
}

Upvotes: -1

Related Questions