<?php
$a = 1;
$b = 1;

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] output:

int(1)
int(1)
a and b are the same
*/

$a = 1;
$b = 0;

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] Output

int(1)
int(0)
a and b are NOT the same
*/

$a = "these are the same";
$b = "these are the same";

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] Output:

string(18) "these are the same"
string(18) "these are the same"
a and b are the same
*/

$a = "these are NOT the same";
$b = "these are the same";

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] output:

string(22) "these are NOT the same"
string(18) "these are the same"
a and b are NOT the same
*/

/*
The results of the examples above are just as we expected,
but let’s look what happens when we compare a string to an integer:
*/

$a = "1";
$b = 1;

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] output:

string(1) "1"
int(1)
a and b are the same
*/

/*
It looks like PHP is trying to be “helpful” and
the comparison is done with the string casted to an integer.
Now lastly, let’s look at what happens when
we compare two strings that look like integers
written in scientific notation:
*/

$a = "0e111111111111111111111111111111";
$b = "0e222222222222222222222222222222";

var_dump($a);
var_dump($b);

if ($a == $b) { print "a and b are the same\n"; }
else { print "a and b are NOT the same\n"; }

/*
[o] output:

string(32) "0e111111111111111111111111111111"
string(32) "0e222222222222222222222222222222"
a and b are the same
*/

/*
You can see in the above that even though “$a” and “$b” are
both of type string and are clearly different values,
the use of the loose comparison operator results in
the comparison evaluating as true, since “0ex” will
always be zero when these are cast to integers by PHP.
This is known as Type Juggling.
*/

?>

results matching ""

    No results matching ""