Validate optional input parameters with if(!empty) I have a function which accepts four parameters, which are all optional. Once they're received, it validates using if(!empty).

$subject = (empty($params['subject'])) ? '' : addslashes(trim(strip_tags($params['subject'])));
$message = (empty($params['message'])) ? '' : addslashes(htmlentities($params['message']));
$userIdArray = (!empty($params['users']) &amp;&amp; is_array($params['users'])) ? array_map('intval', $params['users']) : array();
$messageId = (empty($params['id'])) ? null : intval($params['id']);

$validMessage = true;



$valHelper = new validation();

if(!empty($message)){
    $validMessage = ($valHelper-&gt;validateMessageTextLength($message)) ? true : false;
}

if(!empty($subject) &amp;&amp; $validMessage){
    $validMessage = ($valHelper-&gt;validateMessageSubjectTextLength($subject)) ? true : false;
}

if($messageId &amp;&amp; $validMessage){
    $validMessage = ($valHelper-&gt;validateMessageId($messageId)) ? true : false; 
}

if ($validMessage) {

    // go to save method 
    $messageDbHelper = new Message_MessageDbHelper();
    $messageDbHelper-&gt;saveMessage($subject, $message)   
}  else {
    // show a common error message
}


As you can see, I'm giving a common error message and in a scenario where $message fails in validation then the rest of the if(!empty) statements become an extra overhead.

I need this code to be more optimized. Or is there a better way to do this?

EDIT-

save method is something similar to below

public function saveMessage($subject='', $message=''){
            try {
                $query = 'INSERT INTO message(subject, message) VALUES ("'.$subject.'", "'.$message.'")';
                return $this-&gt;dbAdapter-&gt;query($query)-&gt;rowCount();
            } catch (Exception $ex) {
                throw $ex;
            }
}
I am very concerned about all the mangling that you are doing with addslashes(trim(strip_tags(…))) and addslashes(htmlentities(…)).  It's almost certainly wrong, but I can't tell you what would be right without knowing exactly how those variables get used.