Movatterモバイル変換


[0]ホーム

URL:


PHP 8.5.0 Alpha 2 available for testing
    String »
    « Execution

    Logical Operators

    Logical Operators
    ExampleNameResult
    $a and $bAndtrue if both$a and$b aretrue.
    $a or $bOrtrue if either$a or$b istrue.
    $a xor $bXortrue if either$a or$b istrue, but not both.
    ! $aNottrue if$a is nottrue.
    $a && $bAndtrue if both$a and$b aretrue.
    $a || $bOrtrue if either$a or$b istrue.

    The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (SeeOperator Precedence.)

    Example #1 Logical operators illustrated

    <?php

    // --------------------
    // foo() will never get called as those operators are short-circuit

    $a= (false&&foo());
    $b= (true||foo());
    $c= (falseandfoo());
    $d= (trueorfoo());

    // --------------------
    // "||" has a greater precedence than "or"

    // The result of the expression (false || true) is assigned to $e
    // Acts like: ($e = (false || true))
    $e=false||true;

    // The constant false is assigned to $f before the "or" operation occurs
    // Acts like: (($f = false) or true)
    $f=falseortrue;

    var_dump($e,$f);

    // --------------------
    // "&&" has a greater precedence than "and"

    // The result of the expression (true && false) is assigned to $g
    // Acts like: ($g = (true && false))
    $g=true&&false;

    // The constant true is assigned to $h before the "and" operation occurs
    // Acts like: (($h = true) and false)
    $h=trueandfalse;

    var_dump($g,$h);
    ?>

    The above example will outputsomething similar to:

    bool(true)bool(false)bool(false)bool(true)

    Found A Problem?

    Learn How To Improve This PageSubmit a Pull RequestReport a Bug
    add a note

    User Contributed Notes14 notes

    315
    Lawrence
    17 years ago
    Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

    For example:

    $a = 0 || 'avacado';
    print "A: $a\n";

    will print:

    A: 1

    in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

    This means you can't use the '||' operator to set a default value:

    $a = $fruit || 'apple';

    instead, you have to use the '?:' operator:

    $a = ($fruit ? $fruit : 'apple');
    dumitru at floringabriel dot com
    8 years ago
    In addition to what Lawrence said about assigning a default value, one can now use the Null Coalescing Operator (PHP 7). Hence when we want to assign a default value we can write:

    $a = ($fruit ?? 'apple');
    //assigns the $fruit variable content to $a if the $fruit variable exists or has a value that is not NULL, or assigns the value 'apple' to $a if the $fruit variable doesn't exists or it contains the NULL value
    thisleenobleNOSPAMPLEASE at mac dot com
    8 years ago
    In order to kind of emulate the way javascript assigns the first non-false value in an expression such as this:

    var v = a || b || c || d;

    I wrote a little helper method that I put in a function dump library (here presented as a bare function):

    <?php
    functioneither($a,$b){
    $val=$a?$a:$b;
    /*
    Yes, I know the fixed parameters in the function
    are redundant since I could just use func_get_args,
    but in most instances I'll be using this a replacement
    for the ternary operator and only passing two values.
    I don't want to invoke the additional process below
    unless I REALLY have to.
    */
    $args=func_get_args();
    if(
    $val===false&&count($args) >2){
    $args=array_slice($args,2);

    foreach(
    $argsas$arg){
    if(
    $arg!==false){
    $val=$arg;
    break;
    }
    }
    }
    return
    $val;
    }
    ?>

    Now instead of:

    $v = $a ? $a : $b;

    I write:

    $v = either($a, $b);

    but more importantly, instead of writing:

    $v = $a ? $a : ($b ? $b : $c);

    I write:

    $v = either($a, $b, $c);

    or indeed:

    $v = either($a, $b, $c, $d, $e, $f, $g, $h);
    pepesantillan at gmail dot com
    17 years ago
    worth reading for people learning about php and programming: (adding extras<?php ?> to get highlighted code)

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

    ...
    <?php
    // "||" has a greater precedence than "or"
    $e=false||true;// $e will be assigned to (false || true) which is true
    $f=falseortrue;// $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=trueandfalse;// $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 "=", so

    <?php
    $f
    =falseortrue;

    //is like writting

    ($f=false) ortrue;

    //and

    $e=false||true;

    is the sameas

    $e= (false||true);

    ?>

    same goes for "&&" and "AND".

    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.
    martinholtcbi at gmail dot com
    2 years ago
    In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis" operator.

    #"/manual/vote-note.php?id=125830&page=language.operators.logical&vote=up" title="Vote up!">up
    13
    egst
    4 years ago
    In response to Lawrence about || always returning a boolean:

    Instead of

    $x ? $x : 'fallback'

    you can also use the "elvis operator":

    $x ?: 'fallback'

    which is useful in cases, where the left-hand side of the ternary operator is too long type, is too complex to calculate twice, or has side-effects.

    It also combines nicely with the ?? operator, which is equivalent to an empty() check (both isset() and `!= false`):

    $x->y ?? null ?: 'fallback';

    instead of:

    empty($x->y) ? $x->y : 'fallback'
    momrom at freenet dot de
    16 years ago
    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().

    <?php
    functiona($x) { echo'Expression '; return$x; }
    function
    b($x) { echo'is '; return$x; }
    function
    c($x) { echo$x?'true.':'false.';}

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

    c(a(true) orb(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':

    <?php
    c
    (min( (bool)a(false), (bool)b(true) ) );
    ?>
    phpnet at zc dot webhop dot net
    12 years ago
    This works similar to javascripts short-curcuit assignments and setting defaults. (e.g. var a = getParm() || 'a default';)

    <?php

    ($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.
    Andrew
    17 years ago
    ><?php
    >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. :/
    samantha at adrichem dot nu
    10 years ago
    <?php
    $res
    |=true;
    var_dump($res);
    ?>

    does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1
    anatoliy at ukhvanovy dot name
    11 years ago
    If you want to use the '||' operator to set a default value, like this:

    <?php
    $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:

    <?php
    $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:
    <?php
    functionfruit($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:

    <?php
    $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!

    <?php
    $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'!
    ?>
    void at informance dot info
    11 years ago
    To assign default value in variable assignation, the simpliest solution to me is:

    <?php
    $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.
    peter dot kutak at NOSPAM dot gmail dot com
    17 years ago
    $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

    ($test = true) and false;

    due to "&&" having a higher precedence than "=" while "and" has a lower one
    brian at zickzickzick dot com
    11 years ago
    This has been mentioned before, but just in case you missed it:

    <?php
    // Defaults --

    //If you're trying to gat 'Jack' from:
    $jack=falseor'Jack';

    // Try:
    $jack=falseor$jack='Jack';

    //The other option is:
    $jack=false?false:'Jack';
    ?>
    add a note
    To Top
    and to navigate •Enter to select •Esc to close
    PressEnter without selection to search using Google

    [8]ページ先頭

    ©2009-2025 Movatter.jp