Newbie problem with If...Else

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Thomas B
Forum Newbie
Posts: 3
Joined: Thu Apr 15, 2004 12:31 pm

Newbie problem with If...Else

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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'.
User avatar
johnperkins21
Forum Contributor
Posts: 140
Joined: Mon Oct 27, 2003 4:57 pm

Post 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> 
?>
Unipus
Forum Contributor
Posts: 409
Joined: Tue Aug 26, 2003 2:06 pm
Location: Los Angeles, CA

Post 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 <
Thomas B
Forum Newbie
Posts: 3
Joined: Thu Apr 15, 2004 12:31 pm

Post 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 ;)
Post Reply