I am executing this statement under while (($data=fgetcsv($this->fin,5000,";"))!==FALSE)
Now what I want in else loop is to throw exception only for data value which did not satisfy the if condition. Right now am displaying the complete row as I am not sure how to throw exception only for data which does not satisfy the value.
Code
if ((strtotime($data[11]) &&strtotime($data[12])&&strtotime($data[16]))!==FALSE
&& ctype_digit($data[0]) && ctype_alnum($data[1]) && ctype_digit($data[2])
&& ctype_alnum($data[3]) && ctype_alnum($data[4]) && ctype_alnum($data[5])
&& ctype_alnum($data[6]) && ctype_alnum($data[7]) && ctype_alnum($data[8])
&& $this->_is_valid($data[9]) && ctype_digit($data[10]) && ctype_digit($data[13])
&& $this->_is_valid($data[14]))
{
//Some Logic
}
else
{
throw new Exception ("Data {$data[0], $data[1], $data[2], $data[3],
$data[4], $data[5], $data[6], $data[7],
$data[8], $data[9], $data[10], $data[11], $data[12],
$data[13], $data[14], $data[16]} is not in valid format");
}
Guidance would be highly appreciated as to how can I throw exception only for data which did not satisfy the if value.
Why not separate the tests ? i.e. do each test one by one, and throw an exception if a specific test fails ?
Copy-pasting from your code, it would probably look like this :
This way :
And, as a possibility, you could (if needed) thrown different kind of exceptions, depending on the test that failed (i.e. one kind of exception for dates, one for integers, …) — in some cases, that might be useful.
Edit after the comment : more full example
Yes, you can validate field by field, and still work line by line.
You just have to wrap your testing code in a try/catch block, that’s inside the loop that goes line by line ; a bit like that :
With that :
EDIT: (By Yacoby)
Rather than having endless if statments, you could just define which elements should be checked by which function and then process them in a loop. That way it avoids having 16 if statements.
Code example: