Php logical operator and or

Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).

Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and — (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? : , which takes three values; this is usually referred to simply as «the ternary operator» (although it could perhaps more properly be called the conditional operator).

A full list of PHP operators follows in the section Operator Precedence. The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated.

User Contributed Notes 9 notes

of course this should be clear, but i think it has to be mentioned espacially:

’cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN — after that — compare the success of this with the value of $c

Читайте также:  Php прочитать часть файла

maybe usefull for some tricky coding and helpfull to prevent bugs 😀

Operator are used to perform operation.

Operator are mainly divided by three groups.
1.Uniary Operators that takes one values
2.Binary Operators that takes two values
3.ternary operators that takes three values

Operator are mainly divided by three groups that are totally seventeen types.
1.Arithmetic Operator
+ = Addition
— = Subtraction
* = Multiplication
/ = Division
% = Modulo
** = Exponentiation

2.Assignment Operator
= null coalescing

14.Clone new Operator
clone new = clone new

16.yield Operator
yield = yield

17.print Operator
print = print

Other Language books’ operator precedence section usually include «(» and «)» — with exception of a Perl book that I have. (In PHP «<" and ">» should also be considered also). However, PHP Manual is not listed «(» and «)» in precedence list. It looks like «(» and «)» has higher precedence as it should be.

Note: If you write following code, you would need «()» to get expected value.

$bar = true ;
$str = «TEST» . ( $bar ? ‘true’ : ‘false’ ) . «TEST» ;
?>

Without «(» and «)» you will get only «true» in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It’s due to precedence, probably.

The variable symbol ‘$’ should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won’t confuse the parser. [http://www.php.net/manual/en/language.variables.variable.php]

If you use «AND» and «OR», you’ll eventually get tripped up by something like this:

$this_one = true ;
$that = false ;
$truthiness = $this_one and $that ;
?>

Want to guess what $truthiness equals?

If you said «false» . it’s wrong!

«$truthiness» above has the value «true». Why? «=» has a higher precedence than «and». The addition of parentheses to show the implicit order makes this clearer:

( $truthiness = $this_one ) and $that ;
?>

If you used «&&» instead of and in the first code example, it would work as expected and be «false».

This also works to get the correct value, as parentheses have higher precedence than » default»>$truthiness = ( $this_one and $that );
?>

Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

$a = 2 ;
echo (
$a == 1 ? ‘one’ :
$a == 2 ? ‘two’ :
$a == 3 ? ‘three’ :
$a == 4 ? ‘four’ : ‘other’ );
echo «\n» ;
// prints ‘four’
?>

You need to add brackets to get the results you want:

echo ( $a == 1 ? ‘one’ :
( $a == 2 ? ‘two’ :
( $a == 3 ? ‘three’ :
( $a == 4 ? ‘four’ : ‘other’ ) ) ) );
echo «\n» ;
//prints ‘two’
?>

The scope resolution operator . which is missing from the list above, has higher precedence than [], and lower precedence than ‘new’. This means that self::$array[$var] works as expected.

A quick note to any C developers out there, assignment expressions are not interpreted as you may expect — take the following code ;-

$a =array( 1 , 2 , 3 );
$b =array( 4 , 5 , 6 );
$c = 1 ;

print_r ( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.

A variable is a container that contain different types of data and the operator operates a variable correctly.

  • Language Reference
    • Basic syntax
    • Types
    • Variables
    • Constants
    • Expressions
    • Operators
    • Control Structures
    • Functions
    • Classes and Objects
    • Namespaces
    • Enumerations
    • Errors
    • Exceptions
    • Fibers
    • Generators
    • Attributes
    • References Explained
    • Predefined Variables
    • Predefined Exceptions
    • Predefined Interfaces and Classes
    • Predefined Attributes
    • Context options and parameters
    • Supported Protocols and Wrappers

    Источник

    Php logical operator and or

    worth reading for people learning about php and programming: (adding extras to get highlighted code)

    about the following example in this page manual:
    Example#1 Logical operators illustrated

    .
    // «||» has a greater precedence than «or»
    $e = false || true ; // $e will be assigned to (false || true) which is true
    $f = false or true ; // $f will be assigned to false
    var_dump ( $e , $f );

    // «&&» has a greater precedence than «and»
    $g = true && false ; // $g will be assigned to (true && false) which is false
    $h = true and false ; // $h will be assigned to true
    var_dump ( $g , $h );
    ?>
    _______________________________________________end of my quote.

    If necessary, I wanted to give further explanation on this and say that when we write:
    $f = false or true; // $f will be assigned to false
    the explanation:

    «||» has a greater precedence than «or»

    its true. But a more acurate one would be

    «||» has greater precedence than «or» and than «=», whereas «or» doesnt have greater precedence than » default»>$f = false or true ;

    If you find it hard to remember operators precedence you can always use parenthesys — «(» and «)». And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.

    Evaluation of logical expressions is stopped as soon as the result is known.
    If you don’t want this, you can replace the and-operator by min() and the or-operator by max().

    c ( a ( false ) and b ( true ) ); // Output: Expression false.
    c ( min ( a ( false ), b ( true ) ) ); // Output: Expression is false.

    c ( a ( true ) or b ( true ) ); // Output: Expression true.
    c ( max ( a ( true ), b ( true ) ) ); // Output: Expression is true.
    ?>

    This way, values aren’t automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren’t sure the values are already boolean, you have to convert them ‘by hand’:

    c ( min ( (bool) a ( false ), (bool) b ( true ) ) );
    ?>

    This works similar to javascripts short-curcuit assignments and setting defaults. (e.g. var a = getParm() || ‘a default’;)

    ( $a = $_GET [ ‘var’ ]) || ( $a = ‘a default’ );

    ?>

    $a gets assigned $_GET[‘var’] if there’s anything in it or it will fallback to ‘a default’
    Parentheses are required, otherwise you’ll end up with $a being a boolean.

    > > your_function () or return «whatever» ;
    > ?>

    doesn’t work because return is not an expression, it’s a statement. if return was a function it’d work fine. :/

    This has been mentioned before, but just in case you missed it:

    //If you’re trying to gat ‘Jack’ from:
    $jack = false or ‘Jack’ ;

    // Try:
    $jack = false or $jack = ‘Jack’ ;

    //The other option is:
    $jack = false ? false : ‘Jack’ ;
    ?>

    $test = true and false; —> $test === true
    $test = (true and false); —> $test === false
    $test = true && false; —> $test === false

    NOTE: this is due to the first line actually being

    due to «&&» having a higher precedence than «=» while «and» has a lower one

    If you want to use the ‘||’ operator to set a default value, like this:

    $a = $fruit || ‘apple’ ; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)’apple’ == TRUE)
    ?>

    instead, you have to use the ‘?:’ operator:

    $a = ( $fruit ? $fruit : ‘apple’ ); //if $fruit evaluates to FALSE, then $a will be set to ‘apple’
    ?>

    But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
    function fruit ( $confirm ) if( $confirm )
    return ‘banana’ ;
    >
    $a = ( fruit ( 1 ) ? fruit ( 1 ) : ‘apple’ ); //fruit() will be called twice!
    ?>

    But since «since PHP 5.3, it is possible to leave out the middle part of the ternary operator» (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:

    $a = ( $fruit ? : ‘apple’ ); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to ‘apple’
    ?>

    But remember that a non-empty string ‘0’ evaluates to FALSE!

    $fruit = ‘1’ ;
    $a = ( $fruit ? : ‘apple’ ); //this line will set $a to ‘1’
    $fruit = ‘0’ ;
    $a = ( $fruit ? : ‘apple’ ); //this line will set $a to ‘apple’, not ‘0’!
    ?>

    To assign default value in variable assignation, the simpliest solution to me is:

    $v = my_function () or $v = «default» ;
    ?>

    It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:
    * if the left side is false, null, 0, or an empty string, the right side must be evaluated and, again, because ‘or’ has low precedence, $v is assigned the string «default»
    * if the left side is none of the previously mentioned values, the logical operation ends and $v keeps the return value from my_function()

    This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his solution (parenthesis and double pipe) doesn’t take advantage of the «or» low precedence.

    NOTE: «» (the empty string) is evaluated as a FALSE logical operand, so make sure that the empty string is not an acceptable value from my_function(). If you need to consider the empty string as an acceptable return value, you must go the classical «if» way.

    In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: «Elvis» operator.

    JavaScript:
    let a = false;
    let b = false;
    let c = true;
    let d = false;
    let e = a || b || c || d;
    // e === c

    $a = false ;
    $b = false ;
    $c = true ;
    $d = false ;
    $e = $a ?: $b ?: $c ?: $d ;
    // $e === $c
    ?>

    Credit to @egst and others for the insight. This is merely a rewording for (formerly) lost JavaScript devs like myself.

    $res |= true ;
    var_dump ( $res );
    ?>

    does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1

    Источник

Оцените статью