Archive for the ‘PHP’ Category

Displaying a person’s age in PHP

Tuesday, November 13th, 2007

In case you’re looking for a quick function to display the age of someone based on their birthdate, you may come across this script.

Well, that doesn’t work. Here’s a correct way to return an age:

//calculate years of age (input string: YYYY-MM-DD)
function age_in_years($birthday){
  list($year,$month,$day) = explode("-",$birthday);
  $year_diff  = date("Y") - $year;
  $month_diff = date("m") - $month;
  $day_diff   = date("d") - $day;
  if (($month_diff < 0) || (($month_diff <= 0) && ($day_diff < 0)))
     $year_diff--;
  return $year_diff;
}