views:

82

answers:

3

Im using an if statement to determine what to return in a function, but it seems to be not working the way i want it to.

function DoThis($dogs, $cats){
// do something with dogs, pet them perhaps.

$reg = $dogs[0];
$nate = $dogs[1];

if($cats = "dave"){return $reg;}
if($cats = "tom"){return $nate;}

}

$cats is a string (if that helps), and when entered it doesn't yield any return. If i manually set a return, that works, but the above doesnt for some reason.

+6  A: 

To test for equality, use the == (double equals) operator instead of the = (single equals) operator.

For example:

if("dave" == $cats){return $reg;}
if("tom"  == $cats){return $nate;}
Justin Ethier
Write the variable on the right side and you get a parse error if you forget a =. e.g. `if ('dave'==$cats ) { `
VolkerK
Good call, I just updated my answer. This is a great style once you get in the habit, although every example of an if statement you'll see always does it the other way...
Justin Ethier
+6  A: 

You're using the assignment operator instead of the comparison operator. Try the following instead.

 $cats == "dave"
 $cats == "tom"

When you say

 if($cats = "dave") { ... }

you're really saying

  1. Assign the value "dave" to the variable $cats
  2. If the variable $cats is true after assignment, return true. Otherwise, return false

It's a common mistake, and something tha plagues old hands and new hands alike.

Alan Storm
+2  A: 

You need to use == to compare.

= is an assignment, so it has the effect of setting $cats to "dave" and then (because the expression evaluates to "dave", which is non-empty) it treats the if statement as being "if (true) ..." and executes the contained code.

Jason Williams