开发者

PHP's '===' operator

I have code as

$url = $_GET['q'];
$string = "search_text";
$pos = strpos($url, $string);

Then I use the following to check for the presence of the search_text开发者_如何学C in the URL. If it is present, I want it to hide the HTML fields

if ($pos !== true) {
  // Generate HTML elements
}

However it does not work. Basically, I want to hide certain HTML elements when search_text is present in the URL using the '===' operator for comparing the $pos generated during the strpos operation.


$pos!==true is exactly the opposite of what you want to test for: strpos() will never return true, but either a number or false.

Use

if ($pos === false)


The === operator means exactly equal. Meaning that it must be the same type as well as have the same value.

strpos($url,$string); // Return an integer
true; // is a boolean

An integer > 0 is == true, but not === true

Alternatively you could use:

$pos = strpos($url, $string);

if($pos !== false) // $string not in URL
if($pos == true)   // $string is in URL


Using === or !== to check for true/false means that the variable you are checking will need to be a boolean (i.e. only true or false).


Add one confusing case: between != and !==

$bool1 = false;
if($bool1 != '') {
  echo "I thought it came here";
}
else {
  echo "Actually it came here";
}

Because $bool1's type BOOLEAN is different than STRING, so they are not comparable.

That's why echo "Actually comes here"; while if($bool1 !== '') returns true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜