The Humble Rat
The Humble Rat

Reputation: 4696

PHP Catch Error

I need to be able to catch an error. I have the following code

if($call['status_id'] != '' && $call['datetime_required'] != '')
{
   //do stuff
}
else
{
  // tell them how it failed
}

How would I go about displaying the section on which ti failed. So for example I can return a dynamic error message ie

return 'You did not fill in the field $errorField';

Where

$errorField

Is the if check on which it failed.

UPDATE

I currently code like so

if($call['status_id'] != '')
{
    if ($call['datetime_required'] != '')
    {
      //do stuff
    }
    else
    {
      // tell them it failed due to the second condition
    }
}
else
{
   // tell them it failed due to the first condition
}

But would like to do the check in one line and change the message depending on where ti failed.

Note @jack had already posted his answer before this update.

Upvotes: 1

Views: 85

Answers (2)

Jack
Jack

Reputation: 2830

if($call['status_id'] != '')
{
    if ($call['datetime_required'] != '')
        //do stuff
    }
    else
    {
        // tell them it failed due to the second condition
    }
}
else
{
  // tell them it failed due to the first condition
}

Upvotes: 2

OneOfOne
OneOfOne

Reputation: 99195

I'm not sure I fully understand you, you mean something like this?

function check($call, $req_fields) {
    $failed = array();
    foreach($req_fields as $field) {
        if(!$call[$field]) {
            $failed[] = $field;
        }
    }
    if(count($failed)) {
        return join(', ', $failed) . ' are required.';
    }
    return 'success?' ;
}

$message = check($call, array('status_id', 'datetime_required'));

Upvotes: 3

Related Questions