Age calculation in PHP

A PHP equivalent of my Javascript function to get the number of years passed since someone's birthday... i.e. Age. This is a useful and commonly sought-after addition to a web-designers toolbox. Storing age in a database should never be done. It should always be derived from the date of birth. This function would then come in useful to determine the age.

The following function simply subtracts the difference in years between Now and the birthdate in question, and then adjusts it by a year if the month and day of the birthday fall earlier in the year.

It doesn't validate the date, and it only deals in whole number years meaning babies ages in months are not considered.

Another upgrade to be considered would be the addition of a possible date of death. A persons posthumous age will be then be based on the complete years between date of birth and date of death..

To use this function in your web-page, copy the above script snippet and paste it either before the HTML or XML page has begun, or in a file by itself which can then be 'included' or 'required' in a similar place. In any event it is good practive to ensure the function is present before it may be called.

You can then call the function from any point by passing the function a date string in the format yyyy-mm-dd which is the most common and safe format to use for dates. It is of course the native format for the MySQL date datatype..

 



Return to PHP Articles