Can someone explain to me the difference between =
, ==
, and ===
? I think using one equal sign is to declare a variable while two equal signs is for a comparison condition and lastly three equal signs is for comparing values of declared variables.
views:
119answers:
7
+1
A:
You are right that =
is the assignment operator. The other two are comparison operators that you can read more about here.
klausbyskov
2010-01-14 10:42:43
+10
A:
You have =
the assignment operator, ==
the 'equal' comparison operator and ===
the 'identical' comparison operator.
$a = $b Assign Sets $a to be equal to $b.
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
For more info on the need for ==
and ===
, and situations to use each, look at the docs.
gnarf
2010-01-14 10:43:18
+2
A:
= assignment operator
== checks if two variables have the same value
=== checks if two variables have the same value AND if their types are the same
Silvio Donnini
2010-01-14 10:44:42
+2
A:
=
is the assignment operator==
is the comparison operator (checks if two variables have equal values)===
is the identical comparison operator (checks if two variables have equal values and are of the same type).
Rich Adams
2010-01-14 10:44:57
+1
A:
Everyone else have clarified .. I just want to add an example to clarify it more ..
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
infant programmer
2010-01-14 10:53:51
+1
A:
Maybe you can better comprehend the difference between == and === with an example that involves automatic casting:
echo '"5 is not a number" == 5'."\n";
if("5 is not a number" == 5) {
echo "maybe there is something wrong here\n";
} else {
echo " The integer and the string are different\n";
}
echo '"5 is not a number" === 5'."\n";
if("5 is not a number" === 5) {
echo "maybe there is something wrong here\n";
} else {
echo " The integer and the string are different\n";
}
Eineki
2010-01-14 10:56:18
Perfect example :)
gnarf
2010-01-14 10:58:08