Calculate Age


 / Published in: PHP
 

URL: http://www.bigbold.com/snippets/posts/show/1310

With this function you can calculate the age of a person

Example: echo "Age is: " . birthday ("1984-07-05"); Result will be (23 Feb 2005) = "Age is: 20" calculate years of age (input string: YYYY-MM-DD)

  1. <?php
  2. /*
  3. Calculate Age
  4.  
  5. With this function you can calculate the age of a person
  6.  
  7. Example:
  8. echo "Age is: " . birthday ("1984-07-05");
  9.  
  10. Result will be (23 Feb 2005) = "Age is: 20"
  11.  
  12. calculate years of age (input string: YYYY-MM-DD)
  13.  
  14. */
  15. function birthday ($birthday)
  16. {
  17. list($year,$month,$day) = explode("-",$birthday);
  18. $year_diff = date("Y") - $year;
  19. $month_diff = date("m") - $month;
  20. $day_diff = date("d") - $day;
  21. if ($month_diff < 0) $year_diff--;
  22. elseif (($month_diff==0) && ($day_diff < 0)) $year_diff--;
  23. return $year_diff;
  24. }
  25.  
  26. echo birthday("1980-07-02");
  27.  
  28. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: riacharda on April 4, 2011

Oh yeah that's common sense....why didn't i think of that..?? :P

Nice function. Definitely a keeper.

You need to login to post a comment.