Search code examples
phpboolean-operations

Operating with booleans in PHP


Well, I come from compiled languages as Java and now I am trying to deal with PHP in some specific areas. Today, I have created a "test form" in order to know how to check for valid values, and now I have a little problem.

Suppose that I have multiple fields to evaluate, using a boolean variable I would like to do something like this:

//ASSUMING THAT ALL IS CORRECT
$correct =  true;

$correct &= is_ok($name);
$correct &= is_ok($last_name);
$correct &= is_ok($nickname);
$correct &= is_ok($best_friend);

if (!$correct) {
    //AT LEAST ONE FIELD IS INCOMPLETE
}
else
{
    // EVERYTHING IS OK
}

function is_ok($field){
    return !empty($field);
}

The problem that I am issuing is that &= looks like is not working correctly. Do I need to use another boolean operator?


Solution

  • Always read manual first:

    Bitwise operatiors != Logical operators

    I think you are looking for this:

    //ASSUMING THAT ALL IS CORRECT
    $correct =  true;
    
    $correct = $correct && is_ok($name);
    $correct = $correct && is_ok($last_name);
    $correct = $correct && is_ok($nickname);
    $correct = $correct && is_ok($best_friend);
    

    You should start form tutorials, basic lessons, basic documentation to avoid that kind of questions.