Reputation: 35
Why does the following code always return true?
<?php
$v = "dav6d";
if($v = "david") {
echo "smith";
}
?>
Upvotes: 2
Views: 309
Reputation: 3677
for avoiding such type mistakes, use the variable in second position(right side of comparison operator(here '==
')) just like below
if("david"==$v) {
echo "smith";
}
It helps by producing syntax error message in-case, when you mistakenly put '=
' instead of '==
'
Upvotes: 2
Reputation:
This line:
if($v = "david") {
is using an assignment (i.e. a single =
sign) which will return the result of $v, "david"
, which is a truthy value. If you want to do a comparison use ==
or ===
Upvotes: 11
Reputation: 1312
if($v = "david")
is assigning, not comparing
$v="david"; // This code assign "david" to $v
$v=="david"; // This code compares $v vs "david"
Upvotes: 5
Reputation: 2241
Because you're setting $v
to "david"
in the if statement. Use ==
instead:
<?php
$v = "dav6d";
if($v == "david") {
echo "smith";
}
?>
Upvotes: 3