Logical operators php true or false

前端 未结 4 1652
旧时难觅i
旧时难觅i 2021-01-21 09:39

As a php neewbie , I try to read a lot of other people´s code in order to learn. Today I came across a line like this :

if ( stripos($post_to_check->post_cont         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 09:57

    PHP is a loosely typed language. == match the both values and === match the values as well as the data type of values.

    if (8 == '8') // returns true
    

    Above condition just match the values not the data type hence if evaluate to TRUE

    if (8 === '8') // returns false
    

    and this one check both value and data type of values hence this if evaluate to FALSE

    you use === where you want to check the value and data type both and use == when you need to compare only values not the data type.

    In your case,

    The stripos returns the position of the sub string in the string, if string not found it returns FALSE.

    if ( stripos($post_to_check->post_content, '[' . $shortcode) !== false )
    

    The code above check sub string inside string and get evaluate to TRUE only when the sub string found. If you change it to

    if ( stripos($post_to_check->post_content, '[' . $shortcode) != false )
    

    and when the sub string found at the 0 position the if evaluate to FALSE even when sub string is there in the main string. Then the condition will become like this

    if ( 0 != false )
    

    and this will evaluate to FALSE because the 0 is considered as FALSE

    So you have to use there !==

    if ( 0 !== false )
    

    This will compare the values and data type of both values The value 0 is an integer type and the false is boolean type, hence the data type does not match here and condition will be TRUE

    PHP manual page states these comparison operator you should check this once.

提交回复
热议问题