2009-12-03 6 views
0

다음 중 하나를 선택하는 방법을 알고 싶습니다. 내 양식에 다음과 같은 확인란이 있습니다. 이름 중 하나를 선택하지 않고 확인합니다.값을 확인 중입니다

<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

+1

이 코드를 사용하면 로그 파일에 많은 경고가 나타납니다. – Yacoby

5

사용 isset() 또는 array_key_exists(). 두 함수는 값이 null 인 경우 키가 존재하더라도 isset이 false를 반환한다는 점에서 매우 약간의 차이가 있습니다. 그러나,이 경우에 가능

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

또는 문제가되지해야 당신이 PHP 5.3가있는 경우 약간 느리지 만 더 우아한 솔루션 (안된)입니다

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

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



더 나은 :

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

원하는 경우 프로그래밍 방식에 만족합니다.

+0

이 $ val을 (를) isset에 포함해야합니까? – Andy

+0

그래, 나쁘다. 결정된. – Yacoby

관련 문제