Why is if else statement not working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dragrid
    New Member
    • Jan 2009
    • 29

    Why is if else statement not working

    Code:
    <?php
    
    
    fwrite(STDOUT, "do you want ans in cel ? type y or N to continue \n");
    //$handle = fread(STDIN, 80);
    $ansincel =fgets(STDIN);
    echo " Plz enter number \n";
    //$handle1 = fread(STDIN, 80);
    $numdeg = fgets(STDIN);
    
    if ($ansincel = 'y')
    {
    	$tc = ((5/9)*($numdeg - 32)); // convert to degrees celcius
    	fwrite(STDOUT, " the degree in cel is $tc ");
    } 
    else
    {
    	$tf = ((9/5)*($numdeg + 32));   // convert to degrees fahrenheit
    	fwrite(STDOUT, " the degree in far is $tf ");
    }
    ?>
    Last edited by Niheel; Jun 30 '10, 06:51 PM. Reason: please use code tags to display code
  • Niheel
    Recognized Expert Moderator Top Contributor
    • Jul 2005
    • 2432

    #2
    change

    Code:
    if ($ansincel = 'y')
    to

    Code:
    if ($ansincel == 'y')
    niheel @ bytes

    Comment

    • dragrid
      New Member
      • Jan 2009
      • 29

      #3
      Originally posted by kub365
      change

      Code:
      if ($ansincel = 'y')
      to

      Code:
      if ($ansincel == 'y')
      Kub 365 Much appreciated

      Comment

      • dragrid
        New Member
        • Jan 2009
        • 29

        #4
        Anyone,
        Trying to find out why when i made change above ( from = 'y' to == 'y' ) it skips the if solution and keep executing the else portion

        Comment

        • nathj
          Recognized Expert Contributor
          • May 2007
          • 937

          #5
          I might be missing something but perhaps it should do that. It may be worth changing your if condition to enforce case on both sides of the operator:
          Code:
          if (strtoupper($ansincel) == 'Y')
          then you have ruled out any case issues. If you are still not sure what is going on throw in some echo statements just before the if:
          Code:
          echo("ansincel in upper case =" . strtoupper($ansincel));
          This will show what the value is before you run your conditional statement.
          Hope that helps you out.
          nathj

          PS If you want more output without having to echo variables all over the place you could write them to a log file. I've got a class that will do that if you need it.

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            it may happen, that hitting enter does not only submit the input, but also appends a line feed character, thus your string would be "y\n", which doesn’t match "y".

            try var_dump($ansin cel); to check the variable’s content.

            Comment

            Working...