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
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.
!==
is a comparison that doesn't only compare the value, but also the type of both variables.
It is used here because stripos
can return false
when no hit was found, but also 0
when a hit was found in the first character of the string.
==
is unable to distinguish those two cases (they are both "falsy"), so you have to use ===
when working with stripos
. There's a warning in the manual:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
The difference between !==false
and ==true
is the difference between an identical/not-identical and equal/non-equal comparison in PHP.
Please see the Comparison Operators in the PHP Manual what the difference between Identical and Equal is.
Note: ==true and ===true are different.
I think !==false is similar to ===true, so only explain ==true and ===true. For the first ==, it is equal in value, thus 1 == true, 0==false. for ===, it is "identical" in PHP, namely, equal in value, and also in type.
thus, if the result is at 0th position, result should be true; however, if use ==true, it will not work as 0!= true.
For example, stripos('a sheep', 'a') if you use ==true, the result is wrong as it is at first place.