PHP true & 'true' difference

后端 未结 5 663
再見小時候
再見小時候 2021-01-13 02:31

Quick question. Is there a difference between

$success = true;

and

$success = \'true\';

I know they are n

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 03:12

    Any non-empty string evaluates to true and an empty string evaluates to false. The following script might shed some light for you:

    ';
    
    if('false' == true) {
      echo "'false' == true";
    } else {
      echo "'false' != true";
    }
    
    echo '
    '; if('foo' == true) { echo "'foo' == true"; } else { echo "'foo' != true"; } echo '
    '; if('false' == false) { echo "'false' == false"; } else { echo "'false' != false"; } echo '
    '; if('' == true) { echo "'' == true"; } else { echo "'' != true"; } echo '
    '; if('' == false) { echo "'' == false"; } else { echo "'' != false"; } ?>

    Here is the output:

    'true' == true
    'false' == true
    'foo' == true
    'false' != false
    '' != true
    '' == false
    

    As requested, here are some more examples comparing == with === for various values.

    'true' vs. true
    "; if('true' == true) { echo "'true' == true
    "; } else { echo "'true' != true
    "; } if('true' === true) { echo "'true' === true
    "; } else { echo "'true' !== true
    "; } echo "
    'false' vs. true
    "; if('false' == true) { echo "'false' == true
    "; } else { echo "'false' != true
    "; } if('false' === true) { echo "'false' === true
    "; } else { echo "'false' !== true
    "; } echo "
    1 vs. true
    "; if(1 == true) { echo "1 == true
    "; } else { echo "1 != true
    "; } if(1 === true) { echo "1 === true
    "; } else { echo "1 !== true
    "; } echo "
    0 vs. false
    "; if(0 == false) { echo "0 == false
    "; } else { echo "0 != false
    "; } if(0 === false) { echo "0 === false
    "; } else { echo "0 !== false
    "; } echo "
    1 vs. 'true'
    "; if(1 == 'true') { echo "1 == 'true'
    "; } else { echo "1 != 'true'
    "; } if(1 === 'true') { echo "1 === 'true'
    "; } else { echo "1 !== 'true'
    "; } echo "
    empty string '' vs. false
    "; if('' == false) { echo "'' == false
    "; } else { echo "'' != false
    "; } if('' === true) { echo "'' === false
    "; } else { echo "'' !== false
    "; } ?>

    Output:

    'true' vs. true

    'true' == true
    'true' !== true
    

    'false' vs. true

    'false' == true
    'false' !== true
    

    1 vs. true

    1 == true
    1 !== true
    

    0 vs. false

    0 == false
    0 !== false
    

    1 vs. 'true'

    1 != 'true'
    1 !== 'true'
    

    empty string '' vs. false

    '' == false
    '' !== false
    

提交回复
热议问题