How to Calculate Age with PHP

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

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

8 Responses to “How to Calculate Age with PHP”

  1. Sheffield Website Design March 31, 2011 at 3:28 pm #

    Would this not be a lot easier? :
    [code]
    <?php
    $year = date(‘Y’);
    $dateofbirth = "1988";

    $age = $year – $dateofbirth;
    print $age;
    ?>
    [/code]

    twitter: @mgpwr

    • quicoto March 31, 2011 at 3:36 pm #

      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

    • Sumair January 2, 2013 at 6:24 pm #

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

      thanks bro.

      • Rick January 2, 2013 at 7:59 pm #

        Way to go, glad it worked 😉

  2. Sheffield Website Design March 31, 2011 at 3:56 pm #

    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?

    • quicoto March 31, 2011 at 4:02 pm #

      You just need to call the function with the year-month-day 😉

      [code]<?php echo birthday("1988-11-20"); ?>[/code]

  3. SF October 18, 2011 at 11:57 am #

    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.

    [code]if ( ( $day_diff < 0 && $month_diff == 0 ) || $month_diff < 0)[/code]

  4. sujeet jaiswara April 27, 2012 at 3:11 pm #

    very nice notes for age calculation!!!

Leave a Reply

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