开发者

PHP 'if' statement spanning multiple lines?

I've been trying to get this to work but I keep getting parsing errors:

if (isset($_POST['submit'])) {
    if ( isset($_POST['agree']) == false  || 
         isset($_POST['name'] == false    || 
         isset($_POST['email'] == false   ||  
         isset($_POST['title'] == false   ||  
         isset($_POST['program'] == false || 
         isset($_POST['course'] == false  ||  
         isset($_POST['file'] == false    ||) {
        echo ' <font color="red"> Please complete all required fields </font><br><br> ';
    }
}

Is it possible to do something like this in 开发者_如何学GoPHP? It's to make my code more readable.


Yes, it's perfectly possible, but you have a last trailing || with no following expression and you're missing a bunch of closing ), which is giving you the parse error.

Also, you can abbreviate that to

if (!isset($_POST['agree'], $_POST['name'], ...))

or

if (array_diff(array('agree', 'name', ...), array_keys($_POST)))

Please note though that all this is probably not testing what you want to test. If you have a form, all those fields will be set. Unless the user actively manipulates the form, all fields will be submitted with the value "" (an empty string), which makes isset return true. You're either looking for empty or for more customized tests.


Umm, if you correct the parentheses and leave out the last ||, this is valid php code:

if (isset($_POST['submit'])) {
   if (!isset($_POST['agree']) || 
       !isset($_POST['name']) || 
       !isset($_POST['email']) ||  
       !isset($_POST['title']) ||  
       !isset($_POST['program']) || 
       !isset($_POST['course'])  ||  
       !isset($_POST['file'])
   ) {
       echo '<font color="red">Please complete all required fields</font><br>';
   }
}

By the way, the <font> element has been deprecated, use CSS instead.


Wouldn't it be simpler to do it like this?

foreach(array('submit','agree','name','email','title','program','course','file') as $value) {
    if(!isset($_POST[$value])) {
        /* insert form incomplete routine here */
        }
    }


Your are missing the closing parentheses for almost all of your issets. You also have an extra '||' at the end.

Note: the error message says this very clearly:

 Parse error: syntax error, unexpected T_IS_EQUAL, expecting ',' or ')' in ... on line 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜