检查值是否存在

And*_*ndy 0 php

我的表单中有以下复选框,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>
Run Code Online (Sandbox Code Playgroud)

Yac*_*oby 5

使用isset()array_key_exists().这两个函数确实有很小的区别,如果值为null,即使键存在,isset也返回false.但是,在这种情况下无关紧要

if ( isset($_POST['branding']) || isset($_POST['print']) ){
    //...
}
Run Code Online (Sandbox Code Playgroud)

或者可能更好

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

if ( $hasSomethingSet ){
    //...
}
Run Code Online (Sandbox Code Playgroud)



如果你有PHP 5.3,那么(未经测试)稍慢但更优雅的解决方案:

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

这取决于你喜欢它的函数式编程是多么满意.