user623990
user623990

Reputation:

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 PHP? It's to make my code more readable.

Upvotes: 4

Views: 15862

Answers (4)

Bob Smith
Bob Smith

Reputation: 151

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 */
        }
    }

Upvotes: 4

deceze
deceze

Reputation: 522451

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.

Upvotes: 16

Karoly Horvath
Karoly Horvath

Reputation: 96276

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

Upvotes: 2

phihag
phihag

Reputation: 288140

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.

Upvotes: 15

Related Questions