Fields are required, except if all fields are empty I have a group of four inputs, the first three are required, the fourth is optional.



$fieldA
$fieldB
$fieldC
$fieldD #Optional


So to validate the inputs, I just use this:

if($fieldA === '' || $fieldB === '' || $fieldC === '') {
    #error
}


That works pretty well, except there is a special case: If all four inputs are empty, the input is still valid.

That special case complicates the if condition quite a bit:

if(($fieldA !== '' || $fieldB !== '' || $fieldC !== '' || $fieldD !== '')
    &amp;&amp; ($fieldA === '' || $fieldB === '' || $fieldC === '')) {
    #error
}


The condition in the first pair of parenthesis makes sure that at least one field is not empty, while the rest of the condition makes sure that none of the required fields is empty.

Is there some sneaky way to simplify that if statement that I did not think of?
You have two situations where input is invalid:


fieldD is empty and one or more are empty
fieldD is not empty and one ore more are empty


This makes that you have to check for different situations and so your if-statement cannot really be shortened to one statement.

What you also can do is loop over the fields and do a count of the empty fields and validate this:

$emptyFields = 0;

foreach(array($fieldA, $fieldB, $fieldC, $fieldD)as $field) {
    if ($field === '') {
        $emptyFields++;
    }
}

if ($emptyFields === 4 || $emptyFields === 0 || ($emptyFields === 1 &amp;&amp; $fieldD === '')) {
    //input is VALID
}