rv20 Posted May 23, 2009 Share Posted May 23, 2009 I have 3 input fields wich are posted to a php script, now variety of conditions could happen, field 1 could be blank flield 2 couldbe blank field 3 could be blank all 3 could be blank 1 & 2 coulld be blank 2 & 3 blank etc etc or instead of blank they could have disallowed charcters. Now i want to verify with php and not js, so i could make many IF / ELSEIF statements and build a final string that is send back, but this is a lot of code and messy is there a better shorter way of doing it? I could post back and say, there are errors please try again but i want to point out an exact list of all errors which means checking everthing. Quote Link to comment https://forums.phpfreaks.com/topic/159404-making-shorter-work-of-many-if-statement/ Share on other sites More sharing options...
cunoodle2 Posted May 23, 2009 Share Posted May 23, 2009 If one of them is blank is that ok? I would just do.. <?php if ($field1 == "" || $field2 == "" || $field3 == "") echo "error all three fields are required"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/159404-making-shorter-work-of-many-if-statement/#findComment-840828 Share on other sites More sharing options...
RussellReal Posted May 23, 2009 Share Posted May 23, 2009 try something like this: <?php $fields = array('fname','lname','phone'); $valids = array("/^[a-z'-]+$/i","/^[a-z'-]+$/i","/^1?\s?[\.\)]?\s?\d{3}\s?[\.-]?\s?\d{3}\s?[\.-]?\s?\d{4}$/"); foreach ($fields as $k => $v) { if ($_POST[$v]) { if (!preg_match($valids[$k],trim($_POST[$v]))) { // error, field doesn't pass validation break; } } else { // error, field isn't filled in break; } // field passes validations } ?> Quote Link to comment https://forums.phpfreaks.com/topic/159404-making-shorter-work-of-many-if-statement/#findComment-840899 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.