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; }
Code language: PHP (php)

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

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

  • Would this not be a lot easier? :

    <?php $year = date('Y'); $dateofbirth = "1988"; $age = $year – $dateofbirth; print $age; ?>
    Code language: HTML, XML (xml)

    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.


    • $year = date('Y'); $dateofbirth = $_POST["txtage"]; $age = $year - $dateofbirth;
      Code language: PHP (php)

      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 just need to call the function with the year-month-day 😉

      <?php echo birthday("1988-11-20"); ?>
      Code language: HTML, XML (xml)
  • 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)
    Code language: PHP (php)
  • very nice notes for age calculation!!!

Leave a Reply

Add <code> Some Code </code> if you need to.