Search code examples
phpfunctionif-statementconstruct

Functions in construct statement


I am just coding something and wanted to know how I can include a function in a construct.

if (!formatPhone($phone) && !empty($phone)) {
    $e = 1;
    $e_message .= '<li>The phone number is invalid, please use the format (000) 000-0000.</li>';
} else {
    $phone = formatPhone($phone);
}

Can I assign $phone to the formatePhone() output directly in the contruct statement, but still check for a return false;?


Solution

  • You can include an assignment as expression. But in your case you should reorder the test, to check first for emptiness before the value gets reassigned:

    if ( !empty($phone) and !($phone = formatPhone($phone)) ) {
        $e = 1;
        $e_message .= '<li>The phone number is invalid, please use the format (000) 000-0000.</li>';
    }
    

    This would save you the else tree. But more readable this is not. :|