How to Calculate Age with PHP

Found this cool snippet with returns how old is somebody from a given birthday.

function birthday($birthday){ list($year,$month,$day) = explode("-",$birthday); $year_diff = date("Y") - $year; $month_diff = date("m") - $month; $day_diff = date("d") - $day; if ($day_diff < 0 || $month_diff < 0) $year_diff--; return $year_diff; }

Please note there is a lot of variatons and I'm sure it could be done better.

8 comments
  • Would this not be a lot easier? :

    <?php $year = date('Y'); $dateofbirth = "1988"; $age = $year – $dateofbirth; print $age; ?>

    twitter: @mgpwr

    • Well the function I pasted also takes care about the month and day.

      In your function being the 01-01-2011 or 31-12-2011 will return the same age. Wich is wrong, isn’t it? πŸ˜›

      Thanks por posting.

      Regards

    • $year = date('Y'); $dateofbirth = $_POST["txtage"]; $age = $year - $dateofbirth;

      i used this with a little change in ur code, to get value from user, & it worked,

      thanks bro.

  • The title is: ‘How to Calculate Age with PHP’ and my age is 23, my d.o.b is 1988 – so that code for me outputs 23. It is off by the months you are right πŸ™‚

    In your example how do you pass a d.o.b into it? and print the results?

  • You should only care about $day_diff if $month_diff is 0 (same month), or you’ll end up substracting from $year_diff even if only $day_diff is below 0.

    if ( ( $day_diff < 0 && $month_diff == 0 ) || $month_diff < 0)
  • very nice notes for age calculation!!!

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*