-2

The example code is ok.

if ($xxx != false) {
    echo 'xxxxxxxxxxx';
} else {
    echo 'aaaaaaaaaaa';
}

// result: xxxxxxxxxxx


if ($xxx !== 0) {
    echo 'xxxxxxxxxxx';
} else {
    echo 'aaaaaaaaaaa';
}

// result: aaaaaaaaaaa

But this one confuses me

if ($xxx != 0) {
    echo 'xxxxxxxxxxx';
} else {
    echo 'aaaaaaaaaaa';
}
// result: aaaaaaaaaaa

$xxx is string, why this code returns me false? I have read the document http://www.php.net/manual/en/types.comparisons.php but still don't understand about it.

Terry Lin
  • 2,082
  • 16
  • 19
  • 7
    What's the value of $xxx when the comparison occurs? We can't help you without knowing that. In the meantime [maybe you'll find your answer here](http://stackoverflow.com/q/672040/6096242). –  Dec 31 '16 at 16:23
  • $xxx is bool type ? – Dobe Lee Dec 31 '16 at 16:28

4 Answers4

0

if assigned value was this: $xxx='0' (string type numeric value), then the condition if ($xxx != 0) will return FALSE; That is, it is trying to compare with it's numeric values.

CASE-1:

$xxx = '0';
if ($xxx != 0) {
    echo 'xxxxxxxxxxx';
} else {
    echo 'aaaaaaaaaaa';
}
// result: aaaaaaaaaaa

CASE-2:

$xxx = '0';
if ($xxx !== 0) {
    echo 'xxxxxxxxxxx';
} else {
    echo 'aaaaaaaaaaa';
}
// result: xxxxxxxxxxx
Reza Mamun
  • 5,137
  • 36
  • 36
0

take a look at http://php.net/manual/en/types.comparisons.php for string

if your string is null then the behavior is the same that in your quetion

Loose comparisons with ==

NULL --> TRUE

Strict comparisons with ===

NULL --> FALSE
scaisEdge
  • 124,973
  • 10
  • 73
  • 87
0

Because != is not a clever one. It cant determine exactly whether this value is string type or boolean type.

You should use !== instead if you want exact comparison

0
$var1 = false;  // yes
if ($var1 == 0) echo 'yes'; else echo 'no';

$var2 = 0;  // yes  integer convert to boolean
if ($var2 == false) echo 'yes'; else echo 'no';

$var3 = '0';  // yes  string 2 integer 2 boolean
if ($var3 == false) echo 'yes'; else echo 'no';

$var4 = 0;  // no  integer not 2 boolean
if ($var4 === false) echo 'yes'; else echo 'no';

$var5 = '0';  // no  string not 2 integer and not 2 boolean
if ($var5 === false) echo 'yes'; else echo 'no';
Dobe Lee
  • 465
  • 2
  • 12