Conditional statements. Logical operators in PHP Logical operations in a condition

PHP supports the standard logical operators AND and && , OR and || , ! (not) and XOR . Logical operators allow you to compare the results of two operands (a value or an expression) to determine whether one or both return true or false and choose whether to continue executing the script accordingly based on the returned value. Like comparison operators, logical operators return a single Boolean value - true or false, depending on the values ​​on either side of the operator.

Logical OR (OR and ||)

The logical OR operator is denoted as OR or || . It performs a logical OR operation on two operands. If one or both operands are true, it returns true. If both operands are false, it returns false. You probably have a question: why did they make two versions of one operator? The point of the two different variants of the logical OR operator is that they operate with different priorities.

First, let's look at how the || operator works. . And so, if one or both of its operands are true, it returns true . If both operands return false values, it will return false .

The OR operator works the same as the || operator. with one exception, if the OR operator is used with an assignment, it will first evaluate and return the value of the left operand, otherwise it works exactly the same as the || operator. , i.e. if one or both of its operands are true, it returns true . If both operands return false, it will return false .

To make it clearer how they work, let's give the following example:

1 // First the variable is assigned the value false, and then the second operand is evaluated // Priority action: ($var2 = false) or true $var2 = false or true; echo $var2; // false is not printed // ($var3 = 0) or 3 $var3 = 0 or 3; echo "
$var3"; // => 0 ?>

Any comparison and logical operators can be combined into more complex structures:

There is one more important point worth mentioning regarding both the OR and || operators. . The logical OR operator begins its evaluation with its left operand; if it returns true, then the right operand will not be evaluated. This saves execution time, but care must be taken to ensure that code on which the correct operation of the program may depend is not placed in the right-hand operand.

Logical AND (AND and &&)

The logical AND operator is denoted as AND or && . It performs a logical AND operation on two operands. It returns true if and only if both operands evaluate to true . If one or both operands return false , the operator returns false . The meaning of the two different versions of the “logical AND” operator is the same as the two previous operators, namely, that they work with different priorities.

First, let's look at how the && operator works. And so, if both of its operands are true, it returns true . If at least one or both of its operands return false , it will also return false .

The AND operator works the same as the && operator with one exception, if the AND operator is used with an assignment, it will first evaluate and return the value of the left operand, otherwise it works exactly the same as the && operator. If at least one of its operands returns false, it will also return false, and if both operands return false, it will return false.

To understand, let’s now look at how this works in practice:

$bar3"; // => 9 ?>

Exclusive OR (XOR)

The exclusive OR operator is denoted as XOR. It returns true if one and only one of its operands is true. If both operands are true, the operator will return false.

Because the XOR operator has the same precedence as the AND and OR operators (lower than the assignment operator), and it is used in an assignment expression, it first evaluates and returns the value of the left operand.

6 $a1 = 19 xor 5 > 6; var_dump($a1); // => 19 var_dump(true xor true); // false var_dump((2< 3) xor (5 != 5)); // true ?>

Logical NOT (!)

The logical NOT operator, also called negation, is indicated by the sign! . It is a unary operator placed before a single operand. The logical NOT operator is used to invert the logical value of its operand and always returns true or false .

If you need to invert the value of an expression, such as a && b , you will need to use parentheses: !(a && b) . Also with the help of an operator! You can convert any x value to its Boolean equivalent by using the operator: !!x twice.

Last update: 11/1/2015

In PHP we can use various operators: arithmetic, logical, etc. Let's look at each type of operation.

Arithmetic operations

    + (addition operation)

    For example, $a + 5

    - (subtraction operation)

    For example, $a - 5

    * (multiplication)

    For example, $a * 5

    / (division)

    For example, $a / 5

    % (obtaining the remainder of division)

    For example: $a=12; echo $a % 5; // equals 2

    ++ (increment/increase value by one)

    For example, ++$a

    It is important to understand the difference between the expressions ++$a and $a++ . For example:

    $a=12; $b=++$a; // $b is equal to 13 echo $b;

    Here, first, one is added to the value of the variable $a, and then its value is equated to the variable $b. It would be different if the expression looked like this: $b=$a++; . Here, first the value of the variable $a was equal to the variable $b, and then the value of the variable $a was increased.

    -- (decrement/decrease value by one)

    For example, --$a . And also, as in the case of increment, there are two types of recording: --$a and $a--

Assignment Operators

    Equates a variable to a specific value: $a = 5

    Addition followed by assignment of the result. For example: $a=12; $a += 5; echo $a; // equal to 17

    Subtraction followed by assignment of the result. For example: $a=12; $a -= 5; echo $a; // equals 7

    Multiplication followed by assignment of the result: $a=12; $a *= 5; echo $a; // equals 60

    Division followed by assignment of the result: $a=12; $a /= 5; echo $a; // equal to 2.4

    Concatenate rows and assign the result. Applies to two lines. If the variables do not store strings, but, for example, numbers, then their values ​​are converted to strings and then the operation is performed: $a=12; $a .= 5; echo $a; // equal to 125 // identical to $b="12"; $b .="5"; // equal to 125

    Obtaining the remainder of division and then assigning the result: $a=12; $a %= 5; echo $a; // equals 2

Comparison Operations

Comparison operations are usually used in conditional constructions when it is necessary to compare two values ​​and, depending on the result of the comparison, perform certain actions. The following comparison operations are available.

    The equality operator compares two values, and if they are equal, returns true, otherwise returns false: $a == 5

    The identity operator also compares two values, and if they are equal, returns true, otherwise returns false: $a === 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $a != 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $a !== 5

    Compares two values, and if the first is greater than the second, then returns true, otherwise returns false: $a > 5

    Compares two values, and if the first is less than the second, then returns true, otherwise returns false: $a< 5

    Compares two values, and if the first is greater than or equal to the second, then returns true, otherwise returns false: $a >= 5

    Compares two values, and if the first is less than or equal to the second, then returns true, otherwise returns false: $a<= 5

Equality and identity operator

Both operators compare two expressions and return true if the expressions are equal. But there are differences between them. If the equality operation takes two values ​​of different types, then they are reduced to one - the one that the interpreter finds optimal. For example:

Obviously, variables store different values ​​of different types. But when compared, they will be reduced to the same type - numeric. And the variable $a will be reduced to the number 22. And in the end, both variables will be equal.

Or, for example, the following variables will also be equal:

$a = false; $b = 0;

To avoid such situations, the equivalence operation is used, which takes into account not only the value, but also the type of the variable:

$a = "22a"; $b = 22; if($a===$b) echo "equal"; else echo "not equal";

Now the variables will not be equal.

The inequality operators != and !== work similarly.

Logical operations

Logical operations are typically used to combine the results of two comparison operations. For example, we need to perform a certain action if several conditions are true. The following logical operations are available:

    Returns true if both comparison operations return true, otherwise returns false: $a == 5 && $b = 6

    Similar to the && operation: $a == 5 and $b > 6

    Returns true if at least one comparison operation returns true, otherwise returns false: $a == 5 || $b = 6

    Similar to the operation || : $a< 5 or $b > 6

    Returns true if the comparison operation returns false: !($a >= 5)

    Returns true if only one of the values ​​is true. If both are true or neither is true, returns false. For example: $a=12; $b=6; if($a xor $b) echo "true"; else echo "false";

    Here the result of the logical operation will be false since both variables have a specific value. Let's change the code:

    $a=12; $b=NULL; if($a xor $b) echo "true"; else echo "false";

    Here the result will already be true, since the value of one variable is not set. If a variable has the value NULL, then in logical operations its value will be treated as false

Bit operations

Bit operations are performed on individual bits of a number. Numbers are considered in binary representation, for example, 2 in binary representation is 010, the number 7 is 111.

    & (logical multiplication)

    Multiplication is performed bitwise, and if both operands have bit values ​​equal to 1, then the operation returns 1, otherwise the number 0 is returned. For example: $a1 = 4; //100 $b1 = 5; //101 echo $a1 & $b1; // equals 4

    Here the number 4 in the binary system is 100, and the number 5 is 101. Multiply the numbers bit by bit and get (1*1, 0*0, 0 *1) = 100, that is, the number 4 in decimal format.

    | (logical addition)

    Similar to logical multiplication, the operation is also performed on binary digits, but now one is returned if at least one number in a given digit has a one. For example: $a1 = 4; //100 $b1 = 5; //101 echo $a1 | $b1; // equals 5

    ~ (logical negation)

    inverts all bits: if the bit value is 1, then it becomes zero, and vice versa. $b = 5; echo ~$b;

    x<

    x>>y - shifts the number x to the right by y digits. For example, 16>>1 shifts 16 (which is 10000 in binary) one place to the right, resulting in 1000 or 8 in decimal

Concatenating Strings

The dot operator is used to concatenate strings. For example, let's connect several lines:

$a="Hello,"; $b=" world"; echo $a . $b . "!";

If the variables represent other types than strings, such as numbers, then their values ​​are converted to strings and then the string concatenation operation also occurs.

The lesson will cover conditional php statements: the if statement and the switch statement

PHP conditional statements are represented by three main constructs:

  • condition operator if,
  • switch operator switch
  • And ternary operator.

Let's take a closer look at each of them.

PHP if statement

Figure 3.1. Conditional IF statement, short version


Rice. 3.2. IF ELSE Conditional Statement Syntax


Rice. 3.3. Full syntax of the IF elseif conditional statement

Let's summarize:

Full syntax:

if (condition) ( // if the condition is true operator1; operator2; ) elseif(condition) ( operator1; ... ) else ( // if the condition is false operator1; operator2; )

  • The shortened syntax can do not contain parts of the else clause and do not contain an additional elseif condition
  • Instead of the function word elseif, you can write else if (separately)
  • There can be several elseifs in one if construct. The first elseif expression equal to TRUE will be executed.
  • If there is an alternative elseif condition, the else clause must come last in the syntax.

A conditional statement can use a colon: instead of curly braces. In this case, the statement ends with the auxiliary word endif

Rice. 3.4. Conditional statement If and Endif in php

Example:

if($x > $y): echo $x." is greater than ".$y; elseif($x == $y): // when using ":" you cannot write separately else if echo $x." equals ".$y; else: echo $x." not > and not = ".$y; endif;

Important: When using a colon instead of curly braces in a construction, elseif cannot be written in two words!

Logical operations in a condition

The if condition in parentheses may contain the following operations:

Example: check the value of a numeric variable: if it is less than or equal to 10, display a message "a number less than or equal to 10", otherwise display a message "a number greater than 10"


Solution:

$number=15; if ($number<=10) { echo "число меньше или равно 10"; } else { echo "число больше 10"; }

PHP code blocks can be broken, let's look at an example:

Example: Display html code on screen "a equals 4", if the variable $a is really equal to 4


1 Solution:
1 2 3 4

2 Solution:

1 2 3 A equals 4

A equals 4

php job 3_1: Display the translation of colors from English into Russian, checking the value of the variable (in which the color is assigned: $a="blue")


php job 3_2: Find the maximum of three numbers

Comparison operations and the lie rule

The if construct in parentheses must contain a logical expression or variable, which is considered from the point of view of the algebra of logic, returning the values ​​​​either true or false

Those. a single variable can act as a condition. Let's look at an example:

1 2 3 4 $a = 1 ; if ($a) ( echo $a; )

$a=1; if ($a) ( echo $a; )

In the example, the PHP language translator will consider the variable in brackets to be a lie rule:

Rule of LIE or what is considered false:

  • logical False
  • whole zero ( 0 )
  • real zero ( 0.0 )
  • empty line and string «0»
  • array with no elements
  • object without variables
  • special type NULL

Thus, in the considered example, the variable $a is equal to one, accordingly the condition will be true and the operator echo $a; will display the value of the variable.

php job 3_3: a variable a with a string value is given. If a is equal to the name, then print "Hello, name!", if a is equal to an empty value, then output "Hello Stranger!"

Logical constructs AND OR and NOT in the conditional operator

  1. Sometimes it is necessary to provide for the fulfillment of several conditions simultaneously. Then the conditions are combined logical operator AND — && :
  2. $a=1; if ($a>0 || $a>1) ( echo "a > 0 or a > 1"; )

  3. To indicate if a condition is false, use logical operator NOT — ! :
  4. 1 2 3 4 $a = 1 ; if (! ($a< 0 ) ) { echo "a не < 0" ; }

    $a=1; if (!($a<0)) { echo "a не < 0"; }

Switch operator PHP

The switch operator or “switch” replaces several consecutive if constructs. In doing so, it compares one variable with multiple values. Thus, this is the most convenient means for organizing multi-branching.

Syntax:

1 2 3 4 5 6 7 8 9 10 switch ($variable) ( case "value1" : operator1 ; break ; case "value2" : operator2 ; break ; case "value3" : operator3 ; break ; [ default : operator4 ; break ; ] )

switch($variable)( case "value1": operator1; break; case "value2": operator2; break; case "value3": operator3; break; )

  • The operator can check both string values ​​(then they are specified in quotes) and numeric values ​​(without quotes).
  • The break statement in the construction is required. It exits the construct if the condition is true and the operator corresponding to the condition is executed. Without break, all case statements will be executed regardless of their truth.

Rice. 3.5. Conditional Switch statement


Example: an array with full male names is given. Check the first element of the array and, depending on the name, display a greeting with a short name.


Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $names = array ("Ivan" , "Peter" , "Semyon" ) ; switch ($names [ 0 ] ) ( case "Peter" : echo "Hello, Petya!" ; break ; case "Ivan" : echo "Hello, Vanya!" ; break ; case "Semyon" : echo "Hi, Vanya! " ; break ; default : echo "Hi, $names!"; break ; )

$names=array("Ivan","Peter","Semyon"); switch($names)( case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya!"; break ; default: echo "Hello, $names!"; break; )

php job 3_4:

  • Create a $day variable and assign it an arbitrary numeric value
  • Using the switch construct, print the phrase "It's a work day", if the value of the $day variable falls within the range of numbers from 1 to 5 (inclusive)
  • Print the phrase "It's a day off", if the value of the variable $day is equal to the numbers 6 or 7
  • Print the phrase "Unknown Day", if the value of the $day variable does not fall within the range of numbers from 1 to 7 (inclusive)

Complete the code:

1 2 3 4 5 6 7 8 9 10 11 12 ... switch (... ) ( case 1 : case 2 : ... echo "It's a work day"; break ; case 6 : ... default : ... )

Switch(...)( case 1: case 2: ... echo "It's a working day"; break; case 6: ... default: ... )

PHP ternary operator

Ternary operator, i.e. with three operands, has a fairly simple syntax in which to the left of the ? the condition is written, and on the right are two operators separated by the sign: , to the left of the sign the operator is executed if the condition is true, and to the right of the sign: the operator is executed if the condition is false.

condition? operator1 : operator2 ;

PHP supports the following standard logical operators: "AND" and "&&" (logical AND), "OR" and "||" (logical OR), "!" (logical NOT) and "XOR" (exclusive OR). All of them are used in logical expressions to determine one or another course of program execution depending on the result returned by the expression and relate to binary operators, with the exception of the operator "!" , which is unary. When using logical operators, their operands are converted to the Boolean data type (), and the result depends on the given logical values ​​of the operands and the type of logical operator (see table No. 1).

Table No. 1. Logical operators

Difference between "AND" and "&&" operators, and "OR" and "||" is that the "AND" , "OR" and "XOR" operators have a lower precedence, which is even lower than the assignment operators (see PHP operator table).

It is important to understand how the interpreter processes Boolean expressions. If in an expression with the operator "||" the first (left) operand will have the value true or in an expression with the "&&" operator the first operand will have the value false , then the second (right) operand will no longer be calculated. This is due to the fact that the final result in such cases will not change (see table No. 1), and therefore there is no need to spend time processing the code of the second operand. However, you need to be careful not to place code in the right operand on which the correct operation of the program may depend.

The use of logical operators is shown in example No. 2.

false $a=0||false; //Now $a==true, because 5->true and 8->true $a=5& //Now $a==false, because "0"->false $a="0"& //Now $a==true $a=!false; //Now $a==false, because 5->true $a=!5; /* Function foo() will not be called due to shunts */ $a=(false&&foo()); $b=(true||foo()); $c=(false and foo()); $d=(true or foo()); /* Difference "||" from "or" and "&&" from "and" */ //Acts like ($a=(false||true)) $a=false||true; //Acts like (($a=false) or true) $a=false or true; //Acts like ($a=(false&&true)) $a=false& //Acts like (($a=false) and true) $a=false and true; //Now $a==5, acts like (($a=5) xor 0) $a=5 xor 0; //Now $a==5, acts like (($a=5) and 0) $a=5 and 0; //Now $a==5, acts like (($a=5) or 0) $a=5 or 0; //Now $a==true, acts like ($a=(5||0)) $a=5||0; //Now $a==false, acts like ($a=(5&&0)) $a=5& //Now $a==true, acts like ($a=(5 xor 6)) $a=(5 xor 6); ?>

Example No. 2. Using Boolean Operators

>> I have read a few of these responses and quite honestly didn't find one that explained the differences between the "||" and "OR" operators.

The difference is explained in the link to on operator precedence.

The "||" operators are evaluated before assignment ("="), whereas the "or" operators are evaluated after the assignment. In your second example you are telling PHP to first assign the result of "(choice1 != false ? "hah" : "boo")" to $val, then "or" it against the rest of the statement. Try the example below and you will see what I mean (note the extra brackets to enforce precedence):

define ("choice1" , false );
define ("choice2" , "dog" );
define ("default1" , "other" );
$val = array();

$val [ "Test 1" ] = (choice1 != false ? "hah" : "boo" ) || (choice2 != false ? "hah2" : "boo2" ) || (default1 != false ? "hah3" : "boo3" );
$val [ "Test 1b" ] = ((choice1 != false ? "hah" : "boo" ) || (choice2 != false ? "hah2" : "boo2" ) || (default1 != false ? "hah3 " : "boo3" ));
$val [ "Test 2" ] = (choice1 != false ? "hah" : "boo" ) or (choice2 != false ? "hah2" : "boo2" ) or (default1 != false ? "hah3" : " boo3" );
$val [ "Test 2b" ] = ((choice1 != false ? "hah" : "boo" ) or (choice2 != false ? "hah2" : "boo2" ) or (default1 != false ? "hah3" : "boo3" ));

Foreach ($val as $test => $result ) (
print("$test: "); var_dump ($result); print "
\n
\n" ;
}
?>

test at hto dot com

Because the OR shorthand for an if block can produce more
readable code with less typing, it is tempting to produce functions that will return FALSE on failure or some other data type on success. Like mysql_connect, which "Returns a MySQL link identifier on success, or FALSE on failure."

The novice php php developer should avoid creating functions which might produce a FALSE on failure and an integer on success, if there is any chance that the integer might be zero.

blah blah blah;
$i = give_me_liberty () or die("FATAL DB ERROR!" );
blah blah blah;
?>

ironmo67 at yahoo dot com

Discovered a somewhat annoying different between PHP and Perl:


if (! some_function ()) return false ;
?>

cannot be rewritten as the prettier:

function some_function ()( return false ; )
some_function () or return false ;
?>

The following will work however:

function some_function ()( return false ; )
some_function() or die();
?>

Can you guess why? Simply, die() is a function and "return" is a statement (like the difference between print() and echo, sort of). This is really to bad because I find the if(!)() version tired and unreadable, but hey, it"s better than if (some_c_function == 0) ( do something ).

A lot of the discussion below could have been avoided simply by being clear that &, | and ^ are *not* logical operators. That"s why they"re not listed on this page. They"re operators that act on the binary representations of numbers. They do not take logical values ​​(i.e., "true" or "false") as arguments without first converting them to the numbers 1 and 0 respectively. Nor do they return logical values , but numbers. Sure, you can later treat those numbers as though they were logical values ​​(in which case 0 is cast to "false" and anything else is cast to "true"), but that"s a consequence of PHP"s type casting rules, and nothing to do with the behavior of the operators.

If you want logical operations, use logical operators; if you want bitwise operations, use bitwise operators ... using one for the other seems like a good way to make things difficult.

kws_ at hotpop dot com

"Just Because You Can, Doesn't Mean You Should."

I also feel that circumventing short-circuit evaluation and relying on side-effects in conditional expressions is exercising bad style. Writing code that documents itself using clear and straightforward constructs strikes me as a much better practice than using a convoluted and difficult-to-read expression and explaining it with comments (or worse yet, not documenting it at all!) Indeed, source code should be written for the programmer's eyes more so than the computer's.

Utilizing the bitwise operators in a logical context could violate the expectations of the reader and may create confusion because bitwise operators imply bit-field operands.

I also feel that assuming that short-circuit evaluation is best for logical constructs IS within the compiler"s "rights", since when logical operators are used for their intended purpose, the assumptions that short-circuiting makes *ARE* logical, and do (once again, when used correctly) optimize evaluation of logical expressions.

It is not my intention to directly flame or insult any individual, but only to discourage the use of poor style and to encourage new (and even some experienced) programmers to write clear and verbose code, and to think about the programmers, rather than the computers that might end up trying to decipher your creations.

In answer to braintreno:

The second example you brought is the correct way to do it! It is not convoluted logic at all, it is what makes your code readable by not relying on obscure side effects!! It is much easier to read than the first one and it is by far easier to maintain.

For the idea to let a CheckThisOrOther() function echo information to the user alone, you should be stripped of your coding license. If I ever had to maintain on of your scripts, I"d have to hate you.

This is not meant as flame bating as it might sound! Source code is not written for computers to execute, but for coders to read! Keep that at heart and your co-workers will thank you for it!

braintrino

Shadedecho"s post to force evaluation of both OR expression is actually exactly what should be done to suppress short-circuit optimization.

There are many occasions that you don"t want the compiler to short-circuit any evaluation, especially when you want to do an and/or situation. The short-circuit evaluation does an OR operation but not an AND/OR operation!!!

For instance, if I want the check the user's query form to see if the user has missed answering any entry AND/OR if the user had duplicated the same answer for more than one entry, then I need to send the form back to the client informing what I want to be corrected.

Function SomeAnswersAreMissing()
{
...
echo "Oops! You missed answering some questions.";
return TRUE;
}

Function SomeAnswersAreDuplicated()
{
...
echo "Oops! You can answer both the same way.";
return TRUE;
}

If (SomeAnswersAreMissing() || SomeAnswersAreDuplicated())
SendFormAgain();

If I do that, the user will only see the missing answer warning but not the duplicated answer warning, even if both are true. This is not informative to the user because he/she will have to re-submit the form twice before he/she realized everything he/she did wrong, and frustrate the hack out of them. That is not user-friendly.

If (SomeAnswersAreMissing() | SomeAnswersAreDuplicated())
SendFormAgain();

Then both warning messages are sent at the same time, and the user can correct it in one re-send.

Thank shadedecho, I had been looking for a way to override the compiler"s stupid short-circuit optimization. The computer cannot just assume that short-circuiting is the best:(

BTW, of course you can do:

$you_made_a_mistake = false;

If(SomeAnswersAreMissing())

if (SomeAnswersAreDuplicated())
$you_made_a_mistake = true;

If ($you_made_a_mistake)
SendFormAgain();

But that is convoluted logic!!!

hop

Dear Newbie,

(as i don"t see such ideas creeping up in experienced programmers" minds...)

Please don"t pay attention to shadedecho"s post from 14-Mar-2003 04:02! He is heavily relying on obscure side effects, which is not only very bad programming practice, but also does not achieve the optimization he thinks it is.

The proper way to do this


echo $a;
}

Work like shadedecho wants is (although the example as a whole is rather inapt):

$a .= blah();
$a .= blah2();

If ($a) ( echo $a; )

If you read the discussion he links to you will find that he really wanted to get all distinct entries from two different db tables. Even there he is mistaken. The proper way to do this is to process the first table and then process the second table.
This is not only far more readable than the workaround with "|", it is also not the least slower.

shadedecho

It appears (after much frustrating but ultimately helpful searching and discussion on forums like tek-tips) that the
|| and the && are "short-circuited" as has been previously noted BUT the | and & operators (documented by PHP as bitwise operators) behave as their non-short-circuited counter-parts, respectively.

Function blah() (
echo "hello< br>";
return "from blah()< br>";
}

Function blah2() (
echo "world\< br>";
return "from blah2()< br>";
}

If (($a .= blah()) || ($a .= blah2())) (
echo $a;
}

This would result in the following output:

Hello
from blah()

Notice the "world" didn"t get echo"d and the "from blah2()" didn"t get concat"d into the $a variable, because the first assignment to $a was successful, so the "short-circuting" kicks in and the boolean test terminates without evaluating the rest of it.

HOWEVER, if you replace || with just | in that "if" statement, you get the output:

Hello
world
from blah()
from blah2()

Eureka! all parts of the boolean test are evaluated, in expected left-to-right fashion, and following all the normal precedence rules, so far as I can see.

This makes total sense... Using the bitwise operators, what is occurring is the bitwise-level operation on the result of two non-bitwise operations (the assignments). If a non-bitwise operation returns null (in other words, the value being assigned turns out to be null or 0), the bitwise operator would bind to that (or more appropriately, would "see" it) as a "0", otherwise it would see a non-zero (string of bits with at least one "1" in it).

Then a bitwise | is done on the two values, and if either is non-zero (has "1" bits in it) then the result will have those "1" bits in it (non-zero), and the if statement will interpret any non- zero value as true in a boolean test. Likewise, if both operands to the | were null or 0, then the result would be a zero value, which "if" would interpret as false.

The if statement above is doing a bitwise | on (in this case) two non-zero values ​​(with "1"s in it at the bit level), so the | operation returns a non-zero value which is then reinterpreted by the if statement as TRUE!

So, in this special case where you are trying to string together non-short-circuited boolean tests, these operators work on their operands at the bitwise level, and since they are not comparison operators but mathematical operators, they can"t be short- circuited, and the resulting behavior is a non-short-circuited "boolean test".

I know, you must think I am crazy for trying to get around a built-in optimization like this, but I assure you there is a very good reason for it, and if you are interested, you can check out this thread as I have a very long post in there which explains what I was trying to do:

It is the 9th post down, where you will find my description of my database query"ing which i was wanting to optimize.

Which probably isn't what you want.

This may be of aid to those who like their code to read like English, and might think that the precedence differences of these operators are relatively exotic: they aren't.

As for me I ran into this problem because there is no symbolic logical XOR (for instance, no ^^) so I had to use XOR, and then figured that in similar places I"d ought to use AND and OR, and then my code broke:)

So now I"ve got to
$a = ($b xor $c);

Jesse Thompson
bend.com

yohgaki at hotmail dot com

In PHP4, "and", "or", "&&", "||" -- all are "short circuit" like in C/C++. In PHP3, I think it wasn't.

"Short circuit" means language stops evaluation of expression when conditions are determined. (Most language uses short circuit evaluation for logical condition)

$a = true;
$b = false;
if ($a || $b) (
}

This "if" statement only evaluates $a, since $a is true and whole condition must be true. (i.e. if $b is a function instead of value, the function will not be called)

muerte at web-ster dot com

I was hoping to find an operator similar to ||= functions in perl. My first thought would be:

$i = $i or "default"

But or doesn't work like that. If you want to assign a default value to your variables only if they"re not already assigned you CAN however do:

$i or $i = "default"

The first example does NOT work because the or operator is not overloadable like it is in Perl.

dante at heartme dot com


I wanted to do something like this:

$choice1 = "";
$choice2 = "dog";
$default = "other";
$val = $choice1 || $choice2 || $default;

But then $val1 will only contain 1 or 0. Instead I did this:

$choice1 = "";
$choice2 = "dog";
$default = "other";
$val = $choice1 or $choice2 or $default;

Now $val contained the string "dog". That's
weird that "or" is different from "||"...and I would
think that the "||" should be smart enough to handle
strings...the way PERL does. Guess not. Maybe it's
a design choice.