Q:

Strange IF Statement behaviour

I have an IF statement that consists of two separate function calls
passing values to two variables. Obviously if neither value is 'FALSE'
then the code block is executed:
<?php
   class MyValidater {
      static function validateString($string) {
         if (preg_match("/[A-Za-z]+/", $string)) {
            return $string;
         } else {
            return false;
         }
      }
   }

   $firstName = "Daniel";
   $surname = "Simmons";

   // Dodgy IF statement
   if ($first = MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)) {
      print("Success: $first $second");
   } else {
      print("Fail: $first $second");
   }
?>

As you can see both the $first and $second variables should contain
the values held in $firstName and $surname after successfully being
validated by the Static method validateString.
However, the values of the two variables end up: $first = '1' and
$second = "Simmons".
The '1' should be "Daniel" but for some reason $first is being passed
the value '1' or TRUE. If you swap the two assignment statements over
so that $second is evaluated first, you end up with the opposite
outcome as before. $second = '1' and $first = "Daniel"
Can anyone explain why the String value "Daniel" being returned from
the class method is being changed into the int '1' for the first part
of the conditional statement only? I have had a quick look though the
PHP documentation but cannot find an explanation.
For the moment the workaround is to change the return value from the
static method to be true/false and then make $first = $firstName,
etc... upon success. But this involves more code and I would rather
find out why this way does not work.

A:

You need to bracket your expressions:
if (($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))

What's actually happening is this:
if ($first = (MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)))

It would be much clearer to just do this (note this code isn't identical to what you have):
$first = MyValidater::validateString($firstName);
$second = MyValidater::validateString($surname);

if ($first && $second)

A:

&& is higher then = in the operator precedence. add brackets and it will work.
http://www.php.net/manual/en/language.operators.precedence.php
you can read about operator precedence here.
Also, setting values inside of an if condition is usually bad practice. If you add the brackets, you will most probably see why (let $first set to false and $second set to a string) => the first will be evaluated, but since it is false then, it won't process further since it will go to the else anyways. => second will not be set correct if first = false.

