2

I am very confused, because PHP accepts the below condition.

<?php
   $b = true;
   if($b == 'anything') 
      echo 'ok';
   else
      echo 'no';
?>

Well, PHP displays ok. I still don't understand how is it possible.

Maybe, you can clarify it for me.

M. A. Kishawy
  • 4,865
  • 10
  • 43
  • 72
Jérémy Dupont
  • 225
  • 1
  • 4
  • 11
  • 5
    PHP is a loose typed language so casting might occur when possible. Use strict comparisons `$b === 'hello' // false` whenever you can. http://php.net/manual/en/language.types.type-juggling.php – PeeHaa Oct 02 '14 at 12:46
  • 1
    Setting `$b` to `true` and then assigning a value to `$b` are both conditions that fit 'truthiness'. If you need a strict comparison use `===` – Jay Blanchard Oct 02 '14 at 12:46
  • [how-do-the-php-equality-double-equals-and-identity-triple-equals-comp](http://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp) – Mithun Satheesh Oct 02 '14 at 12:48
  • A non-empty string is seen as equivalent to `true` in loose comparisons in PHP, as simple as that. – deceze Oct 02 '14 at 13:24

3 Answers3

5

this should work for you

$b = true;
if($b === 'hello') 
    echo 'ok';
else
    echo 'no';

when using == php will only checks if values are equal, without comparing the values types, when first value is a bool, php will convert both sides to bool, converting any string but the empty string '' and the string '0' will return true, that's why you have to use ===

follow this link to understand comparison in php

MaK
  • 586
  • 4
  • 23
1

Php is not a strictly typed language so the value in the second half of the IF statement is considered a Truthy value. If you want to complare types as well use the "===" comparison. Take a look at the truthy table on this page. http://php.net/manual/en/types.comparisons.php

1

According to the PHP manual on comparison operators (http://php.net/manual/en/language.operators.comparison.php) == checks for "equalness" whereas === checks for identity (which practically means it is of same TYPE and of same VALUE).

When comparing (for equalness) a bool and a string, the string gets casted to a bool. According to the docs:

When converting to boolean, the following values are considered FALSE:
* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string "0"
* an array with zero elements

so your string 'anything' becomes true.

Briareos386
  • 1,697
  • 17
  • 31