Question

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?

Was it helpful?

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.

OTHER TIPS

if (is_ok($name) && is_ok($last_name) && is_ok($nickname) && is_ok($best_friend)) {
  echo "Good.";  
} else{
  echo "Bad.";
}

Or more simply

if (!empty($name) && !empty($last_name) && !empty($nickname) && !empty($best_friend)) {
  echo "Good.";  
} else{
  echo "Bad.";
}

If you really want to write it the way you wanted to write it:

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

& is bitwise operator. For bloolean use &&, like

`$correct =  $correct && is_ok($name);`

because

echo 1 & 2 

gives 0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top