"if" statement misbehaving

Discussion in 'PHP' started by LongHaul, Oct 3, 2006.

  1. #1
    I'm a newbie to PHP, but this seems weird.

    I have in one file:

    <?php
    $longhaul = "no";
    ?>
    Code (markup):
    Then in another file I have this:

    <?php
    if ($longhaul = "yes") {
    print "[COLOR="Red"]The answer is yes[/COLOR]"; }
    ?>
    Code (markup):
    The problem is that, although the if statement is false, it prints "The answer is yes" anyway.

    Other than this, the files are working ok. It's only this if that isn't working.

    I checked the variable with a simple print without the if; it is indeed "no". Can anyone help??? This is so simple and I have tried all I know to try but can't get rid of "The answer is yes".

    Thanks!
     
    LongHaul, Oct 3, 2006 IP
  2. Matts

    Matts Berserker

    Messages:
    195
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Should be:
    <?php
    if ($longhaul == "yes") {
    print "The answer is yes"; }
    ?>

    Matt
     
    Matts, Oct 3, 2006 IP
  3. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #3
    penagate, Oct 3, 2006 IP
  4. vdd

    vdd Peon

    Messages:
    34
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    $longhaul = "yes" always equal `true` as a result of '=' operation.
    So you must use $longhaul == "yes"
     
    vdd, Oct 3, 2006 IP
  5. LongHaul

    LongHaul Peon

    Messages:
    670
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks guys, it works of course!

    I knew the answer would be something super-simple. In my defense however, I'd looked at 3 or 4 online tutorials and none of them had a double == mark. Huh.

    Oh well, thanks for the replies and links. I really try to figure these out before posting ;)
     
    LongHaul, Oct 3, 2006 IP
  6. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #6
    If none of the tutorials you're looking at had double equals for comparisons, I would suggest finding new tutorials!
     
    TwistMyArm, Oct 3, 2006 IP
  7. LongHaul

    LongHaul Peon

    Messages:
    670
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Exactly what I was thinking! I even looked on php.net, but their example used a different sort of structure, so there were only single ='s. Not their fault, just my scanning too quickly, looking at the wrong elements.
     
    LongHaul, Oct 3, 2006 IP
  8. penagate

    penagate Guest

    Messages:
    277
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #8
    I often use = in if() conditions to cache an expression evaluation, or function call, and use the value later.
     
    penagate, Oct 3, 2006 IP