Calculating Age with PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

You would think that determining a person’s age would be a very simple task for a PHP developer.  However, when I asked this question for myself I found a variety of solutions that people posted online.  Many of them used large functions with conditionals and other logic that was hard to follow.  After a significant amount of research, I’ve come to find the shortest and most accurate solution to this question.

function current_age($birthdate) {
    return( floor((time()-strtotime($birthdate))/31536000) );
}

You can pass just about any type date that strtotime() can recognize, which is an added convenience.  If you have a better solution, let’s hear about it in the comments.

If you enjoyed this article, please share it with a friend!

4 Responses to Calculating Age with PHP

  1. Nils says:

    This function doesn’t check for leap years and can’t calculate the correct age in every case.

  2. Cory LaViska says:

    This is true, but it’s very accurate nevertheless. I’m still searching for a 100% perfect solution for calculating age, so please feel free to post if you come up with anything better.

  3. Zerosan says:

    Just a blindshot, didn’t look much at this function, but that should be it. http://de3.php.net/manual/en/datetime.diff.php

    else, well, I use the same function as you, as it is accurate enough for me.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>