mr.smith
mr.smith

Reputation: 35

What does a simple IF always return true?

Why does the following code always return true?

<?php
$v = "dav6d";
if($v = "david") {
echo "smith";
}
?>

Upvotes: 2

Views: 309

Answers (4)

arun
arun

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

user1864610
user1864610

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

Miguel Angel Mendoza
Miguel Angel Mendoza

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

Codecat
Codecat

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

Related Questions