Prevent multiple ifelse statements in php I'm trying to figure out a way to make my code more readable and maintainable. While rewriting some ugly spaghetti code, I stumbled across this:

if($header !== null &amp;&amp; $fieldValue === null)
{
    $errorMessage =  $message . ': row ' . $row . ', header "' . $header . "\"\n";
}
elseif($header === null &amp;&amp; $fieldValue !== null)
{
    $errorMessage =  $message . ': row ' . $row . ', field value "' . $fieldValue . "\"\n";
}
elseif($header === null &amp;&amp; $fieldValue === null &amp;&amp; $row === null)
{
    $errorMessage =  $message . "\n";
}
elseif($header !== null &amp;&amp; $fieldValue !== null)
{
    $errorMessage =  $message . ': row ' . $row . ', header "' . $header . '", value "' . $fieldValue . "\"\n";
}


It must be possible to make this more efficient, but how? Do I use a switch statement? Please enlighten me.
Try something like this

&lt;?php

function buildErrorMessage($message, $row = null, $header = null, $fieldValue = null) {

    if ($row) {
        $message .=  ": row {$row}";
    }

    if ($header) {
        $message .=  ", header {$header}";
    }

    if ($fieldValue) {
        $message .=  ", value \"{$fieldValue}\"";
    }

    return $message;
}

// Tests
echo buildErrorMessage('one');
echo buildErrorMessage('two', 2);
echo buildErrorMessage('three', 3, 'header');
echo buildErrorMessage('four', 4, 'header', 'value');
echo buildErrorMessage('five', null, null, 'value');