Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operators php true or false

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_content, '[' . $shortcode) !== false )

I was wondering what is the difference between !==false and ==true If someone can explain that to me, It would be greatly appreciated. ..and if there is no real difference - what would be the reasons to use the quoted one over the other ??

like image 984
Obmer kronen Avatar asked Jul 10 '26 00:07

Obmer kronen


2 Answers

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.

like image 127
Shakti Singh Avatar answered Jul 13 '26 14:07

Shakti Singh


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.

like image 35
hakre Avatar answered Jul 13 '26 12:07

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!