2009-12-03 169 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