2009-12-03 170 views
0

我的表单中有以下复选框,id想要知道如何检查至少其中一个选中状态,而不更改它们的名称。检查值是否存在

<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> 

回答

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

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

您甚至可以使用布尔值而不是整数,或者只使用if(this || that || foo || bar){} 为什么不能重写表单? – Emyr 2009-12-03 16:43:13

+1

你知道这段代码会在你的日志文件中产生很多警告吗? – Yacoby 2009-12-03 17:43:34

5

使用isset()array_key_exists()。这两个函数的确有很小的差别,如果值为null,即使密钥存在,isset也会返回false。然而,它不应该在这种情况下,不管

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

或者可能更好

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

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



如果你有PHP 5.3,速度较慢,但​​更优雅的解决方案是(未经测试):

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

这取决于您对功能性编程的满意程度,您是否喜欢它。

+0

$ val应该在isset中吗? – Andy 2009-12-03 16:46:29

+0

是的,我的坏。固定。 – Yacoby 2009-12-03 16:48:44