Page 1 of 1

Newbie problem with If...Else

Posted: Thu Apr 15, 2004 12:31 pm
by Thomas B
Good evening everyone. I'm having a little problem with this script I've written to update my age on my website automatically:

Code: Select all

<?php

	$year = date("Y");
	$month = date("n");
	$day = date("j");

	if ($month < "8" and $day < "10") {
	   $age = $year - 1988;
	} else {
	   $age = $year - 1987;
	}

?>

<p><b>How old are you?</b><br>I am <?php echo $age; ?> years old</p>
The problem is that it keeps outputting "17", which is incorrect. From playing around with it I found that it skips the "if" and goes straight for the catch-all "else" condition, hence why I believe the problem lies in the conditions of the "if" statement. But I just can't seem to find what's wrong with it! Any ideas?

I'm just trying to teach myself PHP for the past week or so to give me something else to get my teeth into in the summer holidays, so I'd really appreciate the help.

Posted: Thu Apr 15, 2004 12:39 pm
by feyd
breaking it apart we get:
$month < "8", returns true.
$day < "10", returns false. At least for the past several days or so.
Both conditions have to be true because you are using 'and'.

Posted: Thu Apr 15, 2004 1:00 pm
by johnperkins21
Try this:

Code: Select all

<?php
  $year = date("Y");
   $month = date("n");
   $day = date("j");

   if ($month < "8") {
      if ($day < "10") {
         $age = $year - 1988;
      } else {
         $age = $year - 1987;
       }
   } else {
      $age = $year - 1987;
   }

?>

<p><b>How old are you?</b><br>I am <?php echo $age; ?> years old</p> 
?>

Posted: Thu Apr 15, 2004 1:25 pm
by Unipus
And shouldn't you be using integers instead of strings? I don't actually know if it makes a difference, but it probably doesn't help.

Code: Select all

if ($month <

Posted: Fri Apr 16, 2004 2:12 pm
by Thomas B
johnperkins21: I'll be trying that tonight! Cheers!

Unipus: I think I did get rid of the quotes there once when I was experimenting, and it didn't seem to do any different. I'll look out for that in future though, so thanks for pointing that out ;)

Thanks for your time everyone ;)